当前位置: 首页 > news >正文

java实现多线程的三种方式

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

java中实现多线程的方法有两种:继承Thread类和实现runnable接口

1.继承Thread类,重写父类run()方法

  public class thread1 extends Thread {
 
        public void run() {
                for (int i = 0; i < 10000; i++) {
                        System.out.println("我是线程"+this.getId());
                }
        }
 
        public static void main(String[] args) {
                thread1 th1 = new thread1();
                thread1 th2 = new thread1();
                th1.run();
                th2.run();
        }
     }

run()方法只是普通的方法,是顺序执行的,即th1.run()执行完成后才执行th2.run(),这样写只用一个主线程。多线程就失去了意义,所以应该用start()方法来启动线程,start()方法会自动调用run()方法。上述代码改为:

 public class thread1 extends Thread {
        
        public void run() {
                for (int i = 0; i < 10000; i++) {
                        System.out.println("我是线程"+this.getId());
                }
        }
 
        public static void main(String[] args) {
                thread1 th1 = new thread1();
                thread1 th2 = new thread1();
                th1.start();
                th2.start();
        }
}

通过start()方法启动一个新的线程。这样不管th1.start()调用的run()方法是否执行完,都继续执行th2.start()如果下面有别的代码也同样不需要等待th2.start()执行完成,而继续执行。(输出的线程id是无规则交替输出的)

 

2.实现runnable接口

public class thread2 implements Runnable {
 
        public String ThreadName;
        
        public thread2(String tName){
                ThreadName = tName;
        }
        
        
        public void run() {
                for (int i = 0; i < 10000; i++) {
                        System.out.println(ThreadName);
                }
        }
        
        public static void main(String[] args) {
                thread2 th1 = new thread2("线程A:");
                thread2 th2 = new thread2("线程B:");
                th1.run();
                th2.run();
        }
}

和Thread的run方法一样Runnable的run只是普通方法,在main方法中th2.run()必须等待th1.run()执行完成后才能执行,程序只用一个线程。要多线程的目的,也要通过Thread的start()方法(注:runnable是没有start方法)。上述代码修改为:

public class thread2 implements Runnable {
 
        public String ThreadName;
        
        public thread2(String tName){
                ThreadName = tName;
        }
        
        
        public void run() {
                for (int i = 0; i < 10000; i++) {
                        System.out.println(ThreadName);
                }
        }
        
        public static void main(String[] args) {
                thread2 th1 = new thread2("线程A:");
                thread2 th2 = new thread2("线程B:");
                Thread myth1 = new Thread(th1);
                Thread myth2 = new Thread(th2);
                myth1.start();
                myth2.start();
        }
}

3.使用ExecutorService、Callable、Future实现有返回结果的多线程(JDK5.0以后)
可返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了,再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了。下面提供了一个完整的有返回结果的多线程测试例子,在JDK1.5下验证过没问题可以直接使用。代码如下:

import java.util.concurrent.*;  
import java.util.Date;  
import java.util.List;  
import java.util.ArrayList;  
  
/** 
* 有返回值的线程 
*/  
@SuppressWarnings("unchecked")  
public class Test {  
public static void main(String[] args) throws ExecutionException,  
    InterruptedException {  
   System.out.println("----程序开始运行----");  
   Date date1 = new Date();  
  
   int taskSize = 5;  
   // 创建一个线程池  
   ExecutorService pool = Executors.newFixedThreadPool(taskSize);  
   // 创建多个有返回值的任务  
   List<Future> list = new ArrayList<Future>();  
   for (int i = 0; i < taskSize; i++) {  
    Callable c = new MyCallable(i + " ");  
    // 执行任务并获取Future对象  
    Future f = pool.submit(c);  
    // System.out.println(">>>" + f.get().toString());  
    list.add(f);  
   }  
   // 关闭线程池  
   pool.shutdown();  
  
   // 获取所有并发任务的运行结果  
   for (Future f : list) {  
    // 从Future对象上获取任务的返回值,并输出到控制台  
    System.out.println(">>>" + f.get().toString());  
   }  
  
   Date date2 = new Date();  
   System.out.println("----程序结束运行----,程序运行时间【"  
     + (date2.getTime() - date1.getTime()) + "毫秒】");  
}  
}  
  
class MyCallable implements Callable<Object> {  
private String taskNum;  
  
MyCallable(String taskNum) {  
   this.taskNum = taskNum;  
}  
  
public Object call() throws Exception {  
   System.out.println(">>>" + taskNum + "任务启动");  
   Date dateTmp1 = new Date();  
   Thread.sleep(1000);  
   Date dateTmp2 = new Date();  
   long time = dateTmp2.getTime() - dateTmp1.getTime();  
   System.out.println(">>>" + taskNum + "任务终止");  
   return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】";  
}  
}
代码说明:

上述代码中Executors类,提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口.
public static ExecutorService newFixedThreadPool(int nThreads) 

创建固定数目线程的线程池
public static ExecutorService newCachedThreadPool() 

创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)如果现有线程没有可用的,则创建一个新线程并添加到池中.终止并从缓存中移除那些已有60秒钟未被使用的线程.
public static ExecutorService newSingleThreadExecutor() 

创建一个单线程化的Executor。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 

创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。
ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成.

总结:实现java多线程的2种方式,runable是接口,thread是类,runnable只提供一个run方法,建议使用Thread实现 java多线程,不管如何,最终都需要通过thread.start()来使线程处于可运行状态。第三种方法是听群里的兄弟们介绍的,所以就百度补上了。 

 

转载于:https://my.oschina.net/Tsher2015/blog/487277

相关文章:

  • ava垃圾加收机制和ios的arc有什么区别
  • Linux iostat命令详解
  • 建立完整的单向动态链表(包括初始化、创建、插入、删除、查找、销毁、输出)...
  • 【Go】Linux下使用Sublime Text搭建开发环境
  • 双nginx(主备、主主)反向代理tomcat实现web端负载均衡
  • c# 笔试题及参考答案大全
  • 如果有一天你没有了动力,可以看看
  • winsock 收发广播包
  • Oracle开发中的正则表达式
  • 选择算法
  • 【点杀iOS】深拷贝浅拷贝copy的那些事儿
  • 【性能调优】如何将Hybris启动时间减少30%-50%
  • springJDBC一对多关系,以及Java递归,jsp递归的实现
  • 如何修改myeclipse中web项目的工作路径或默认路径
  • Leetcode——最长不重复子串
  • [PHP内核探索]PHP中的哈希表
  • #Java异常处理
  • 03Go 类型总结
  • CSS 三角实现
  • Github访问慢解决办法
  • github指令
  • js作用域和this的理解
  • PAT A1050
  • vue:响应原理
  • 等保2.0 | 几维安全发布等保检测、等保加固专版 加速企业等保合规
  • 前端性能优化--懒加载和预加载
  • 如何设计一个微型分布式架构?
  • 如何抓住下一波零售风口?看RPA玩转零售自动化
  • 世界编程语言排行榜2008年06月(ActionScript 挺进20强)
  • 主流的CSS水平和垂直居中技术大全
  • PostgreSQL 快速给指定表每个字段创建索引 - 1
  • 不要一棍子打翻所有黑盒模型,其实可以让它们发挥作用 ...
  • 积累各种好的链接
  • # 睡眠3秒_床上这样睡觉的人,睡眠质量多半不好
  • #我与Java虚拟机的故事#连载02:“小蓝”陪伴的日日夜夜
  • (1)安装hadoop之虚拟机准备(配置IP与主机名)
  • (1)虚拟机的安装与使用,linux系统安装
  • (9)目标检测_SSD的原理
  • (Redis使用系列) Springboot 实现Redis 同数据源动态切换db 八
  • (简单有案例)前端实现主题切换、动态换肤的两种简单方式
  • (免费领源码)Java#ssm#MySQL 创意商城03663-计算机毕业设计项目选题推荐
  • (三)uboot源码分析
  • (转)jQuery 基础
  • (转)创业的注意事项
  • @RequestBody与@ModelAttribute
  • [ 数据结构 - C++] AVL树原理及实现
  • []C/C++读取串口接收到的数据程序
  • []FET-430SIM508 研究日志 11.3.31
  • [AAuto]给百宝箱增加娱乐功能
  • [Angular 基础] - 表单:响应式表单
  • [AutoSar]工程中的cpuload陷阱(三)测试
  • [boost]使用boost::function和boost::bind产生的down机一例
  • [C++提高编程](三):STL初识
  • [codeforces]Checkpoints
  • [Google Guava] 2.1-不可变集合