1. 继承Thread类创建线程
package liu;
public class FirstThread extends Thread {
private int i;
// 重写run()方法,run()方法的方法体就是线程执行体
public void run() {
for (; i < 100; i++) {
// 当线程类继承Thread类时, 直接使用this即可获取当前线程
// Thread对象的getName()方法返回当前线程的名字
// 因此可以直接调用getName()方法返回当前线程的名字
System.out.println(getName() + " " + i);
}
}
public static void main(String[] args) {
for (var i = 0; i < 100; i++) {
// 调用Thread的currentTheead()方法获取当前线程
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 20) {
// 创建并启动第一个线程
new FirstThread().start();
// 创建并启动第二个线程
new FirstThread().start();
}
}
}
}
2. 实现Runnable接口创建线程类
package liu;
// 通过实现Runnable接口来创建线程类
public class SecondThread implements Runnable {
private int i = 90;
// run()方法同样是线程执行体
public void run() {
for (; i < 100; i++) {
// 当线程实现Runnable接口时
// 如果想获取当前线程,只能用Thread.currentThread()方法
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
public static void main(String[] args) {
for (var i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 20) {
var st = new SecondThread();
// 使用new Thread(target, name)方法创建新线程
new Thread(st, "新线程1").start();
new Thread(st, "新线程2").start();
}
}
}
}
3. 使用Callable和Future创建线程
package liu;
import java.util.concurrent.*;
//import java.util.concurrent.FutureTask;
public class ThirdThread {
public static void main(String[] args) {
// 创建Callable对象
// var rt = new ThirdThread();
// 先使用Lamada表达式创建Callable<Integer>对象
// 使用FutureTask来包装Callable对象
FutureTask<Integer> task = new FutureTask<>((Callable<Integer>) () -> {
var i = 0;
for (; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
// Call()方法可以有返回值
return i;
});
var cn = new CallableNew();
FutureTask<Integer> task2 = new FutureTask<>(cn);
for (var i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 20) {
// 实质上还是以Callable对象来创建并启动线程的
new Thread(task2, "有返回值的线程").start();
}
}
try {
// 获取线程返回值
System.out.println("子线程的返回值:" + task2.get());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
class CallableNew implements Callable {
// 重写call()方法
public Integer call() {
var i = 0;
for (; i < 120; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
// Call()方法可以有返回值
return i;
}
}