码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA实现多线程的四种方式

时间:2020-02-27 16:10:36      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:返回值   cep   err   oid   executor   继承   返回   exception   call   

1.继承Thread类

public class myThread extends Thread{

  @Override
  public void run() {
    System.out.println("现在的线程是:"+Thread.currentThread());
  }

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

2.实现Runnable接口

public class myRunnable implements Runnable{

  @Override
  public void run() {
    System.out.println("现在的线程是:"+Thread.currentThread());
  }


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

3.实现Callable接口并用FutureTask包装

public class MyCallAble implements Callable<Integer> {
  @Override
  public Integer call() throws Exception {
    System.out.println("现在的线程是:"+Thread.currentThread());
    return null;
  }

  public static void main(String[] args) {
    new Thread(new FutureTask<>(new MyCallAble())).start();
    new Thread(new FutureTask<>(new MyCallAble())).start();
    new Thread(new FutureTask<>(new MyCallAble())).start();
    new Thread(new FutureTask<>(new MyCallAble())).start();
    new Thread(new FutureTask<>(new MyCallAble())).start();
  }
}

 

4.利用Executor类返回的线程

public class ExcutorPool {

  public static void main(String[] args) throws Exception{
    ExecutorService pool = Executors.newFixedThreadPool(10);

    List<Future<Integer>> list=new ArrayList<Future<Integer>>();

    for (int i = 0; i < 10; i++) {
      Future<Integer> future=pool.submit(new Callable<Integer>() {
      public Integer call() throws Exception {
        System.out.println("当前线程为"+Thread.currentThread());
        return null;
      }
      });
      list.add(future);
    }
    //关闭线程池
    pool.shutdown();

    for (Future<Integer> future : list) {
      //此处输出线程结束后的返回值future.get();
    }
  }
}

JAVA实现多线程的四种方式

标签:返回值   cep   err   oid   executor   继承   返回   exception   call   

原文地址:https://www.cnblogs.com/xujuntao/p/12372488.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!