创建线程的三种方式,七种写法:
方式一:(继承Thread)
该方法的好处是this代表的就是当前线程,不需要通过Thread.currentThread()来获取当前线程的引用。
写法1:
public class Test {
static class MyThread extends Thread{
@Override
public void run() {
//线程实现自己的代码
}
}
public static void main(String[] args) throws InterruptedException {
//创建一个线程
MyThread myThread = new MyThread();
//启动线程
myThread.start();
//等待线程执行结束
myThread.join();
}
}
写法2:
public class Test {
public static void main(String[] args) throws InterruptedException {
//创建线程
Thread thread = new Thread(){
@Override
public void run() {
//实现自己的代码
}
};
//启动线程
thread.start();
//等待线程执行结束
thread.join();
}
}
因为java是单继承,所以以上两种方法有很多的局限性,不能继承其他的类,所以很少用。
方式二:(实现 Runnable 接口)
该方法的好处是可以规避类的单继承的限制,但需要通过Thread.currentThread()来获取当前线程的引用。
写法3:
public class Test {
static class MyRunnable implements Runnable{
@Override
public void run() {
//实现自己的代码
}
}
public static void main(String[] args) throws InterruptedException {
MyRunnable myRunnable = new MyRunnable();
//创建一个线程
Thread thread = new Thread(myRunnable);
//启动线程
thread.start();
//等待线程执行结束
thread.join();
}
}
写法4:
public class Test {
public static void main(String[] args) throws InterruptedException {
//创建一个线程
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
//实现自己的代码
}
});
//启动线程
thread.start();
//等待线程结束
thread.join();
}
}
写法5:
下面这种写法(lamada表达式)只有JDK8及之后的版本才可以使用
public class Test {
public static void main(String[] args) throws InterruptedException {
//创建线程
Thread thread = new Thread(()->{
//实现自己的代码
});
//启动线程
thread.start();
//等待线程结束
thread.join();
}
}
写法6:
public class Test {
public static void main(String[] args) throws InterruptedException {
Runnable runnable = new Runnable() {
@Override
public void run() {
//实现自己的代码
}
};
Thread thread = new Thread(runnable);
thread.start();
thread.join();
}
}
方式三:
上面两种方式创建的线程都不支持有返回值的时候使用,下面的写法支持有返回值的时候使用
写法7:
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Test {
static class MyCallable implements Callable<Integer> { //<>里面的类型是返回值的类型
@Override
public Integer call() throws Exception {
//写自己的代码并返回需要返回的值
return 0;
}
}
public static void main(String[] args) throws InterruptedException {
//创建Callable子对象
MyCallable myCallable = new MyCallable();
//接收返回值的容器
//若要使用线程返回的值就在 futureTask 里面取值
FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
//创建线程
Thread thread = new Thread(futureTask);
//启动线程
thread.start();
//等待线程执行结束
thread.join();
}
}