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

实现线程的三种方式:

   (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 {

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

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

你可能感兴趣的:(多线程基础一之(线程的3种实现方式))