创建线程方法
常见的创建线程的方法有三类六种
1. 继承Thread类来实现线程的创建(2种创建方式)
继承Thread类创建线程的缺点:
Java 只能实现单继承,如果该类继承了Thread类,也就无法继承其他类。
方法一:
public class ThreadDemo2 {
static class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程名称:" + Thread.currentThread().getName());
}
}
public static void main(String[] args) {
Thread t1 = new MyThread();
//运行新线程
t1.start();
System.out.println("当前线程名称(主线程):" + Thread.currentThread().getName());
}
}
方法二:
public class ThreadDemo3 {
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run() {
System.out.println("线程名称:" + Thread.currentThread().getName());
}
};
thread.start();
}
}
2. 实现Runnable接口的方式来实现线程的创建(3种创建方式)
弥补了第一类创建方法的缺点,即Java不能多继承,但可以实现多个接口
方法一:
package thread_0425;
/**
* Created by JiaLe on 2021/4/25 19:43
*/
public class ThreadDemo4 {
static class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("线程名称:" + Thread.currentThread().getName());
}
}
public static void main(String[] args) {
//新建一个MyRunnable类
MyRunnable runnable = new MyRunnable();
//新建一个Thread
Thread thread = new Thread(runnable);
//启动thread
thread.start();
}
}
方法二:
package thread_0425;
/**
* Created by JiaLe on 2021/4/25 19:47
*/
public class ThreadDemo5 {
public static void main(String[] args) {
//匿名内部类实现线程
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程名称:" + Thread.currentThread().getName());
}
});
thread.start();;
}
}
方法三:
package thread_0425;
/**
* Created by JiaLe on 2021/4/25 19:49
*/
public class ThreadDemo6 {
public static void main(String[] args) {
//JDK8中的固定写法
//lambda + 匿名 Runnable 的实现方式
Thread thread = new Thread(() -> {
System.out.println("线程名称:" + Thread.currentThread().getName());
});
thread.start();
}
}
3. 实现Callable接口的方式来实现线程的创建(1种创建方式)
可以得到线程执行后的结果
package thread_0425;
import com.sun.deploy.net.proxy.ProxyUnavailableException;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* Created by JiaLe on 2021/4/25 19:54
* 创建并得到线程的执行结果
* 实现Callable接口 + Future 的方式
*/
public class ThreadDemo7 {
static class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int num = new Random().nextInt(10);
System.out.println(Thread.currentThread().getName() + " " + num);
return num;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
//1.创建一个 Callable
MyCallable callable = new MyCallable();
//2.创建一个 FutureTask 对象来接收返回值
FutureTask<Integer> futureTask = new FutureTask<>(callable);
//3.创建 Thread
Thread thread = new Thread(futureTask);
// 启动线程
thread.start();
// 得到线程执行结果
int result = futureTask.get();
System.out.println(Thread.currentThread().getName() + " " + result);
}
}