java 多线程 三种_Java实现多线程的三种方式

1. 继承Thread类

public class Main {

public static void main(String[] args) {

MyThread myThread = new MyThread();

myThread.start();

}

class MyThread extends Thread{

public void run(){

System.out.print("Thread Body");

}

}

继承Thread后,调用start()方法就是执行类类中的run()方法,这也是启动线程的唯一方法。它是一个native方法,当此方法调用以后并不是马上就执行多线程代码,而是把该线程变为可运行Runnable状态,什么时候执行则由操作系统决定。

2. 实现Runnable接口

public class Main {

public static void main(String[] args) {

MyThread myThread = new MyThread();

Thread thread = new Thread(myThread);

thread.start();

}

class MyThread extends otherClass implements Runnable{

public void run(){

System.out.print("Thread Body");

}

}

当类已经继承于别的类而不能继承Thread类时,可以使用实现Runnable接口的方法。但是在这种方法下,要先创建Thread对象,用实现Runnable接口的对象作为参数实例化该Thread对象。

3. 实现Callable接口,重写call()方法

Callable 对象实际属于Executor框架中的功能类,Callable接口和Runnable接口类似,但功能更强大

Callable可以在任务结束后提供一个返回值

Callable中的call()方法可以抛出异常,Runnable中的run()方法则不可以

运行Callable可以拿到一个Future对象,Future对象表示异步计算的结果。它提供了检查计算是否完成的方法。由于线程属于异步计算模型,所以无法从其他线程中得到方法的返回值,在这种情况下,就可以用Future来监视目标线程调用run()方法的情况,当调用Future的get()方法获取结果的时候,当前线程就会阻塞,直到call()方法结束返回结果。

public class Main {

public static void main(String[] args) {

ExecutorService threadPool = Executors.newSingleThreadExecutor();

Future future = threadPool.submit(new MyThread());

try{

System.out.println("Waiting thread to finish");

System.out.println(future.get());

} catch (Exception e){

e.printStackTrace();

}

}

}

class MyThread implements Callable{

public String call() throws Exception{

return "Thread Body";

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值