一、Java创建线程的三种方式:
1.继承Thread类创建线程类
public class Test1 {
public static void main(String[] args) {
MyThread01 t1=new MyThread01();
MyThread01 t2=new MyThread01();
t1.start();
t2.start();
}
}
class MyThread01 extends Thread{
@Override
public void run() {
System.out.println("线程名:"+currentThread().getName());
}
}
运行结果
2.实现Runnable接口
public class Demo2 {
public static void main(String[] args) {
MyThread02 target=new MyThread02();
Thread t1=new Thread(target);
Thread t2=new Thread(target);
t1.start();
t2.start();
}
}
class MyThread02 implements Runnable{
@Override
public void run() {
System.out.println("线程名:"+Thread.currentThread().getName());
}
}
运行结果
3.通过Callable和Future创建线程
import java.util.concurrent.*;
public class Demo3 {
public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
Callable callable=new MyThread03();
FutureTask task1=new FutureTask(callable);
FutureTask task2=new FutureTask(callable);
new Thread(task1).start();
new Thread(task2).start();
Thread.sleep(10);//等待线程执行结束
//task.get() 获取call()的返回值。若调用时call()方法未返回,则阻塞线程等待返回值
System.out.println(task1.get());
System.out.println(task2.get());
//get的传入参数为等待时间,超时抛出超时异常;传入参数为空时,则不设超时,一直等待
System.out.println(task1.get(10L, TimeUnit.MILLISECONDS));
System.out.println(task2.get(10L, TimeUnit.MILLISECONDS));
}
}
class MyThread03 implements Callable{
@Override
public Object call() throws Exception {
System.out.println("线程名:"+Thread.currentThread().getName());
return "实现callable:"+Thread.currentThread().getName();
}
}
运行结果
二、创建线程的三种方式的对比
1、采用实现Runnable、Callable接口的方式创建多线程
优势:
线程类只是实现了Runnable接口或Callable接口,还可以继承其他类。
在这种方式下,多个线程可以共享同一个target对象,所以非常适合多个相同线程来处理同一份资源的情况,从而可以将CPU、代码和数据分开,形成清晰的模型,较好地体现了面向对象的思想。
劣势:
编程稍微复杂,如果要访问当前线程,则必须使用Thread.currentThread()方法。
2、使用继承Thread类的方式创建多线程
优势:
编写简单,如果需要访问当前线程,则无需使用Thread.currentThread()方法,直接使用this即可获得当前线程。
劣势: