Java笔记(11) 多线程

打印 上一主题 下一主题

主题 543|帖子 543|积分 1629

Java原生支持多线程,主要通过以下四种方式实现多线程:

  • 继承Thread类
  • 实现Runnable接口
  • 实现Callable接口
  • 线程池
继承Thread类

通过创建Thread类的子类,并重写run()方法,通过调用start()方法启动线程。
  1. public class TestThread extends Thread {
  2.     @Override
  3.     public void run() {
  4.         //run方法线程体
  5.         for (int i = 0; i < 10; i++) {
  6.             System.out.println("run方法线程体" + i);
  7.         }
  8.     }
  9.     public static void main(String[] args) {
  10.         //main线程,主线程
  11.         TestThread testThread = new TestThread();//创建一个线程对象
  12.         testThread.start();//调用start()方法,启动线程
  13.         for (int i = 0; i < 10; i++) {
  14.             System.out.println("main方法线程体" + i);
  15.         }
  16.     }
  17. }
复制代码

可以看到两个线程的执行过程是混乱的,这就说明两个线程的执行顺序是随机的,并不是按照调用顺序来执行的。
但一般不建议使用继承Thread类的方式实现多线程,因为Java是单继承的,子类继承Thread类之后,会限制后续扩展。


实现Runnable接口

Thread类就实现了Runnable接口,我们也可以实现Runnable接口并实现run()方法来实现多线程。在创建Thread类的时候,将待执行线程作为参数传递,调用start()方法启动。
  1. //实现Runnable接口,并实现run()方法
  2. public class TestThread3 implements Runnable {
  3.     @Override
  4.     public void run() {
  5.         for (int i = 0; i < 5; i++) {
  6.             System.out.println("run 方法线程: " + i);
  7.         }
  8.     }
  9.     public static void main(String[] args) {
  10.         TestThread3 testThread3 = new TestThread3();//创建新线程
  11.         new Thread(testThread3).start();//创建Thread类,并将待执行线程作为参数传递进去,调用start()方法启动
  12.         for (int i = 0; i < 5; i++) {
  13.             System.out.println("main 方法线程: " + i);
  14.         }
  15.     }
  16. }
复制代码

相比于第一种方案,更推荐使用接口方案,继承Runnable接口避免了收到单继承的限制,也方便同一个对象被多个线程使用


实现Callable接口

Callable接口类似于Runnable接口,都是为 其实例可能由另一个线程执行的类 而设计的。 不过相比于Runnable接口实现多线程的方式,实现Callable接口的多线程方式可以返回结果,并可能抛出异常。实现Callable接口并实现call方法。
  1. public class TestCallable implements Callable<Boolean> {
  2.     @Override
  3.     public Boolean call() throws Exception {  //实现call()方法
  4.         for (int i = 0; i < 5; i++) {
  5.             System.out.println("call 方法线程: " + i);
  6.         }
  7.         return true;
  8.     }
  9.     public static void main(String[] args) {
  10.         TestCallable testCallable = new TestCallable();  //创建新任务
  11.         ExecutorService executorService = Executors.newFixedThreadPool(1); //创建线程池
  12.         Future<Boolean> res = executorService.submit(testCallable);  //将任务提交到线程池
  13.         for (int i = 0; i < 5; i++) {
  14.             System.out.println("main 方法线程: " + i);
  15.         }
  16.         executorService.shutdown();  //需要手动关闭线程池服务
  17.     }
  18. }
复制代码


线程池

待编辑...

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

商道如狼道

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表