1. 繼承Thread類創(chuàng)建線程
package liu;
public class FirstThread extends Thread {
private int i;
// 重寫(xiě)run()方法垂攘,run()方法的方法體就是線程執(zhí)行體
public void run() {
for (; i < 100; i++) {
// 當(dāng)線程類繼承Thread類時(shí), 直接使用this即可獲取當(dāng)前線程
// Thread對(duì)象的getName()方法返回當(dāng)前線程的名字
// 因此可以直接調(diào)用getName()方法返回當(dāng)前線程的名字
System.out.println(getName() + " " + i);
}
}
public static void main(String[] args) {
for (var i = 0; i < 100; i++) {
// 調(diào)用Thread的currentTheead()方法獲取當(dāng)前線程
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 20) {
// 創(chuàng)建并啟動(dòng)第一個(gè)線程
new FirstThread().start();
// 創(chuàng)建并啟動(dòng)第二個(gè)線程
new FirstThread().start();
}
}
}
}
2. 實(shí)現(xiàn)Runnable接口創(chuàng)建線程類
package liu;
// 通過(guò)實(shí)現(xiàn)Runnable接口來(lái)創(chuàng)建線程類
public class SecondThread implements Runnable {
private int i = 90;
// run()方法同樣是線程執(zhí)行體
public void run() {
for (; i < 100; i++) {
// 當(dāng)線程實(shí)現(xiàn)Runnable接口時(shí)
// 如果想獲取當(dāng)前線程,只能用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)方法創(chuàng)建新線程
new Thread(st, "新線程1").start();
new Thread(st, "新線程2").start();
}
}
}
}
3. 使用Callable和Future創(chuàng)建線程
package liu;
import java.util.concurrent.*;
//import java.util.concurrent.FutureTask;
public class ThirdThread {
public static void main(String[] args) {
// 創(chuàng)建Callable對(duì)象
// var rt = new ThirdThread();
// 先使用Lamada表達(dá)式創(chuàng)建Callable<Integer>對(duì)象
// 使用FutureTask來(lái)包裝Callable對(duì)象
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) {
// 實(shí)質(zhì)上還是以Callable對(duì)象來(lái)創(chuàng)建并啟動(dòng)線程的
new Thread(task2, "有返回值的線程").start();
}
}
try {
// 獲取線程返回值
System.out.println("子線程的返回值:" + task2.get());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
class CallableNew implements Callable {
// 重寫(xiě)call()方法
public Integer call() {
var i = 0;
for (; i < 120; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
// Call()方法可以有返回值
return i;
}
}