首页 > 技术文章 > 在Java中实现多线程

2227556036Daily 2018-03-22 11:18 原文

Java多线程实现方式主要有四种:继承Thread类、实现Runnable接口、实现Callable接口通过FutureTask包装器来创建Thread线程、使用ExecutorService、Callable、Future实现有返回结果的多线程。

1.继承Thread类

/*
* 凡是要线程执行的任务
* 需要重写父类的run方法
* 特殊方法 这样写在他里面的任务才能被多线程同时启动
*/

 1 package MythreadFirst;
 2 
 3 /**
 4  *1.继承thread类
 5  * @author Daily  growing
 6  *
 7  */
 8 public class GetThread extends Thread{
 9     
10     public void run(){
11         try {
12             Thread.sleep(100);
13         } catch (InterruptedException e) {
14             e.printStackTrace();
15         }
16         /*
17          * Thread.currentThread().getName() 
18          * 获得当前线程的名字
19          * 输出的时候 可以更加仔细观察到哪个线程在执行
20          */
21         System.out.println(Thread.currentThread().getName() + "我是线程中的任务");
22     }
23 }
24
27public static void main(String[] args) throws InterruptedException {
28  GetThread gt = new GetThread();        //创建状态
30  //启动线程 到就绪状态
31  gt.start();//通过start方法 触发run方法
32 }

 

2.实现Runnable接口

/*
* Runnable 不能直接start
* 可以委托给多个Thread 齐头并进
* 委托给Thread 后
* 多个Thread 可能会重复 一起使用

*但是可以大大提高线程的效率

* 凡是要让线程执行的任务

* 重写父类的run方法重写

* 写在它里面的方法 才能被多线程同时启动

*/

 1 package MythreadFirst;
 2 
 3 /**
 4  * @author Daily  growing
 5  */
 6 public class GetThreadOne implements Runnable {
 7     
 8     @Override
 9     public void run() {    
10         System.out.println("我在执行Runnable 接口");    
11     }
12 
13 }
14 
15 
16 public static void main(String[] args) throws InterruptedException {
17 
18     /*
19     *为了启动MyThread,需要首先实例化一个Thread,并传入自己的MyThread实例:
20     */
21     GetThreadOne gto = new GetThreadOne();
22         
23     Thread t = new Thread();
24     t.start();
25                 
26     Thread t1 = new Thread();
27     t1.start();
28 
29 }    

 

3、实现Callable接口通过FutureTask包装器来创建Thread线程

Callable接口(也只有一个方法)定义如下: 

1 public interface Callable<V>   { 
2   V call() throws Exception;  
3  } 
public class SomeCallable<V> extends OtherClass implements Callable<V> {

    @Override
    public V call() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

}
Callable<V> oneCallable = new SomeCallable<V>();   
//由Callable<Integer>创建一个FutureTask<Integer>对象:   
FutureTask<V> oneTask = new FutureTask<V>(oneCallable);   
//注释:FutureTask<Integer>是一个包装器,它通过接受Callable<Integer>来创建,它同时实现了Future和Runnable接口。 
//由FutureTask<Integer>创建一个Thread对象:   
Thread oneThread = new Thread(oneTask);   
oneThread.start();   
//至此,一个线程就创建完成了。

 

4.最后一个实现多线程的方法这里就不说了 , 哈哈

推荐阅读