创建线程的几种方式

2022-11-03  本文已影响0人  糯米团子123
  1. 继承Thread类
public class MyThread extends Thread{
    public void run(){
        for (int i = 0;i<10;i++){
            System.out.println(Thread.currentThread()+":"+i);
        }
    }

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

  1. 实现Runnable接口
public class MyThread implements Runnable{
    @Override
    public void run(){
        for (int i = 0;i<10;i++){
            System.out.println(Thread.currentThread()+":"+i);
        }
    }

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread thread1 = new Thread(myThread,"线程1");
        Thread thread2 = new Thread(myThread,"线程2");
        Thread thread3 = new Thread(myThread,"线程3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
  1. 通过Callable创建线程(异步,可以返回结果)
public class MyThread implements Callable<String> {
    private int count = 20;


    @Override
    public String call() throws Exception {
        for (int i = count ; i > 0 ; i--){
            System.out.println(Thread.currentThread().getName()+"当前数量:"+i);
        }
        return "已无";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<String> callable = new MyThread();
        FutureTask<String> futureTask = new FutureTask<>(callable);
        Thread thread1 = new Thread(futureTask);
        Thread thread2 = new Thread(futureTask);
        Thread thread3 = new Thread(futureTask);
        thread1.start();
        thread2.start();
        thread3.start();

        System.out.println(futureTask.get());
    }
}
  1. 线程池创建
public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建固定数量的线程
        ExecutorService ex = Executors.newFixedThreadPool(5);
        for (int i = 0;i<5;i++){
            ex.submit(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0;j<10;j++){
                        System.out.println(Thread.currentThread().getName()+j);

                    }
                }
            });

        }
        ex.shutdown();
    }
上一篇 下一篇

猜你喜欢

热点阅读