码迷,mamicode.com
首页 > 编程语言 > 详细

多线程基础一之(线程的3种实现方式)

时间:2018-11-04 01:50:43      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:size   ati   eth   extend   throw   阻塞   string   LEDE   main   

实现线程的三种方式:

   (1)继承Thread类,重写Run方法 

class MyThreadDemo extends Thread {
@Override
public void run() {
System.out.println("This is my Thread!");
}
public static void main(String[] args) {
MyThreadDemo thread = new MyThreadDemo();
thread.start();
}
}

(2)实现Runnable接口,重写Run方法
class RunnableThread implements Runnable{

@Override
public void run() {
System.out.println("This is my RunnableThread!");
}
public static void main(String[] args) {
Thread thread = new Thread(new RunnableThread());
thread.start();
}
}
(3)实现callable接口,重写call()方法,并带返回值
public class CallableDemo implements Callable<String> {

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

ExecutorService executorService = Executors.newCachedThreadPool();
CallableDemo callableDemo = new CallableDemo();
Future<String> future = executorService.submit(callableDemo);
//call未执行完
//放一些其他业务逻辑的处理
System.out.println(future.get());//阻塞
executorService.shutdown();
}
@Override
public String call() throws Exception {
return "String"+1;
}
}
 

多线程基础一之(线程的3种实现方式)

标签:size   ati   eth   extend   throw   阻塞   string   LEDE   main   

原文地址:https://www.cnblogs.com/flgb/p/9902655.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!