线程是系统调度的基本单位,引入线程是为了进一步提高系统的并发性,提高CPU的利用率。
创建线程的方法主要有如下三种方式:
(1)继承Thread类创建线程
(2)实现Runnable接口创建线程
(3)使用Callable和Future创建线程
1.继承Thread类创建线程
使用方法1:继承Thread,重写其run()方法
//继承Thread,重写其run()方法
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("MyThread excuted.");
}
}
//主线程直接调用start()启动线程
new MyThread().start();
使用方法2:创建匿名内部类Thread,重写其run()方法
new Thread() {
@Override
public void run() {
System.out.println("Anonymous thread excuted.");
}
}.start();
2.实现Runnable接口创建线程
使用方法:创建一个类Runnable接口的实例,重写其run()方法,并将该类的实例作为创建Thread的入参。
//实现Runnable接口,重写run()方法
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("MyRunnable excuted.");
}
}
//将MyRunnable作为新线程的执行体,并调用线程的start方法。
new Thread(new MyRunnable()).start();
3.使用Callable和Future创建线程
//FutureTask实现了RunnableFuture接口,RunnableFuture既实现了Future接口,还实现了Runnable接口,因此FutureTask可以作为Thread的执行体.
//Callable接口的call()方法相当于是线程的执行体,并且可以自定义返回值。通过get方法获取线程执行的返回值
FutureTask<String> ft = new FutureTask<String>(new Callable<String>() {
@Override
public String call() throws Exception {
return "FutureTask excuted.";
}
});
new Thread(ft).start();//启动线程
try {
System.out.println(ft.get());//使用get方法获取线程执行的返回值
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}