Java多线程是怎么实现的

Java多线程实现方式主要有4种:继承Thread类,实现Runnable接口,实现Callbale接口通过FutureTask包装器来创建Thread线程,使用EcecutorService,callable, Future实现有返回值的多线程

其中前两种执行后额没有返回值,后两种是带返回值的。

1.继承Thread类
Thread类本质上是实现Runnable接口的一个实例,代表一个线程的实例。启动线程的唯一方法是通过Thread类的Srtart()实例方法。start()是一个native方法,它将启动一个新线程,并执行run()方法。这种方式实现多线程很简单,通过自己的类直接extend Thread,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。

public class MyThread extends Thread {  
  public void run() {  
   System.out.println("MyThread.run()");  
  }  
}  

MyThread myThread1 = new MyThread();  
MyThread myThread2 = new MyThread();  
myThread1.start();  
myThread2.start();

2.实现Runnable接口
如果自己的类已经extends另一个类,就无法直接extends Thread,此时,可以实现一个Runnable结口

public class MyThread extends OtherClass implements Runnable {  
  public void run() {  
   System.out.println("MyThread.run()");  
  }  
}  

为了启动MyThread,需要首先实例化一个Thread,并传入自己的MyThread实例

MyThread myThread = new MyThread();  
Thread thread = new Thread(myThread);  
thread.start(); 

3.实现Callable接口通过FutureTask包装器来创建Thread线程
Callabke接口(也只有一个方法)定义如下:

public interface Callable<V>   { 
  V call() throws Exception;  
} 
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.使用ExccutorService,Callable,Future实现有返回结果的线程
ExecutorService,Callable,Future三个接口实际上都是属于Exector框架。返回结果的线程是Jdk1.5种引入的新特征,有了这种新特征就不需要在为了返回值而大费周折了。
可返回值的任务必须实现Callable接口。类似的,无返回值的任务必须实现Runnable接口。
执行Callable任务后,可以获取哟个Future对象,在该对象上调用get就可以获取到Callable任务返回的Object了。
再结合线程池接口EcectorService就可以实现带有返回结果的多线程
注意:get方法是阻塞的,即:线程无返回结果,get方法会一直等待

转载自:https://www.cnblogs.com/felixzh/p/6036074.html

猜你喜欢

转载自blog.csdn.net/qq_41056506/article/details/81781715