Loading

线程创建方式

线程创建方式

Java中创建线程主要有三种方式,分别为继承Thread类、实现Runnable接口、实现Callable接口。

继承Thread类

继承Thread类,重写run()方法,调用start()方法启动线程

public class ThreadTest {

 
public static class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("hello");
    }
}

public static void main(String[] args) {
    MyThread thread = new MyThread();
    thread.start();
}
}

实现 Runnable 接口

实现 Runnable 接口,重写run()方法

public class RunnableTask implements Runnable {
    public void run() {
        System.out.println("Runnable!");
    }

    public static void main(String[] args) {
        RunnableTask task = new RunnableTask();
        new Thread(task).start();
    }
}

实际上Thread中的run方法不重写的话,逻辑就是调用Runnable 的run方法。

实现Callable接口

实现Callable接口,重写call()方法,这种方式可以通过FutureTask获取任务执行的返回值

public class CallerTask implements Callable<String> {
    public String call() throws Exception {
        return "Hello,i am running!";
    }

    public static void main(String[] args) {
        //创建异步任务
        FutureTask<String> task=new FutureTask<String>(new CallerTask());
        //启动线程
        new Thread(task).start();
        try {
            //等待执行完成,并获取返回结果
            String result=task.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}


线程池

public static void main(String[] args) {

    Runnable task1 = new Task1();
    Runnable task2 = new Task2();
    new Thread().start();
    ExecutorService executorService = Executors.newFixedThreadPool(2);
    executorService.execute(task1);
    executorService.execute(task2);
   
}
posted @ 2023-09-01 17:39  花园SON  阅读(2)  评论(0编辑  收藏  举报