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

更多 Java 并发编程方面的文章,请参见文集《Java 并发编程》

继承 Thread 类

run() 方法 VS start() 方法:

run() 方法:普通的成员方法

start() 方法:负责启动一个新的线程,并调用 run() 方法

因此启动线程,需要使用 start() 方法

public class MultiThread_Test {

public static void main(String[] args) {

MyThread mt = new MyThread();

mt.start();

}

}

class MyThread extends Thread {

public void run() {

System.out.println(Thread.currentThread().getName());

}

}

实现 Runnable 接口

实际上 Thread 类也是实现了 Runnable 接口:

class Thread implements Runnable {

启动 Runnable 实例时,需要放在 Thread 中,然后调用 start() 方法

public class MultiThread_Test {

public static void main(String[] args) {

MyRunnable mr = new MyRunnable();

new Thread(mr).start();

}

}

class MyRunnable implements Runnable {

public void run() {

System.out.println(Thread.currentThread().getName());

}

}

实现 Callable 接口

Java 5 开始提供

可以返回结果(通过 Future),也可以抛出异常

需要实现的是 call() 方法

以上两点也是 Callable 接口 与 Runnable 接口的区别

public class MultiThread_Test {

public static void main(String[] args) throws Exception {

ExecutorService es = Executors.newSingleThreadExecutor();

// 自动在一个新的线程上启动 MyCallable,执行 call 方法

Future f = es.submit(new MyCallable());

// 当前 main 线程阻塞,直至 future 得到值

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

es.shutdown();

}

}

class MyCallable implements Callable {

public Integer call() {

System.out.println(Thread.currentThread().getName());

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

e.printStackTrace();

}

return 123;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值