创建多线程的方式

方式1:

  继承Thread创建多线程

class MyThread extends Thread{
    public MyThread(){

    }

    public MyThread(String name){
        super(name);
    }
    
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "继承Thread");
    }
}

 

    public static void main(String[] args) {
        Thread thread1 = new MyThread("A");
        Thread thread2 = new MyThread("B");
        thread1.start();
        thread2.start();
    }

 

方式2:

  实现Runnable接口并使用Thread(Runnable,String)构造方法创建多线程

class MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "实现Runnable创建多线程");
    }
}
   public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();
        Thread thread1 = new Thread(myRunnable, "A");
        Thread thread2 = new Thread(myRunnable, "B");
    }

 

  (可以使用lambda表达式)

   public static void main(String[] args) {
        new Thread(()->{
            System.out.println(Thread.currentThread().getName() + "实现Runnable创建多线程");
        },"A").start();
        new Thread(()->{
            System.out.println(Thread.currentThread().getName() + "实现Runnable创建多线程");
        },"B").start();
    }

 

方式3:

  实现callable接口创建多线程

class MyCallable implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "实现Callable创建多线程");
        return 1024;
    }
}

 

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyCallable());
        new Thread(futureTask,"A").start();
        new Thread(futureTask,"B").start();
        Integer result = futureTask.get();
        System.out.println(result);
    }

     注意:

      1) futureTack.get()方法调用在最后,否则主线程依旧需要等待创建的新线程得出结果后执行语句

      2) 如果多个线程都是由同一个futureTask实例对象创建的,那么Callable接口的call() 方法只会调用一次,返回的结果一致

        

 

方式4:

  使用线程池创建线程

    public static void main(String[] args) {
        int corePoolSize = 2;
        int maximumPoolSize = Runtime.getRuntime().availableProcessors() + 1;
        long keepAliveTime = 1L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(3);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.DiscardPolicy();
        ExecutorService threadPool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,keepAliveTime,unit,workQueue,threadFactory,handler);
        try {
            for (int i = 0; i < 10; i++) {
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "\t办理业务");
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }
    }

 

posted @ 2021-02-26 22:45  樱花葬礼  阅读(57)  评论(0)    收藏  举报