更新時間:2022-09-05 11:11:54 來源:動力節點 瀏覽1192次
Java創建線程的方式有哪些?動力節點小編來給大家介紹三種Java創建線程的方式。
步驟:
a.創建一個類繼承Thread,并重寫run()方法,run()方法體為線程要執行的任務。
b.創建該類的實例對象,即創建了線程對象。
c.調用star()方法來啟動線程。
public class TestThread extends Thread {
private int i = 0;
@Override
public void run() {
for (; i < 10; i++) {
System.out.println(this.getName() + " " + i);
}
}
public static void main(String[] args) {
for (int j = 0; j < 20; j++) {
// 設置線程名稱
Thread.currentThread().setName("主線程");
// 獲取當前線程
System.out.println(Thread.currentThread().getName() + " " + j);
if (j == 5) {
// 創建第一個線程
new TestThread().start();
// 創建第二個線程
new TestThread().start();
}
}
}
}
運行結果
步驟:
a.定義Runnable接口的實現類,重寫run()方法,run()方法體為線程要執行的任務。
b.創建Runnable實現類的實例對象,將tr作為Thread對象的target創建并啟動新線程。
c.調用star()方法來啟動線程。
public class TestRunnable implements Runnable {
private int i = 0;
@Override
public void run() {
for (; i < 10; i++) {
// 實現Runnable接口 只能通過Thread.currentThread().getName()獲取線程名稱
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
public static void main(String[] args) {
for (int j = 0; j < 20; j++) {
// 獲取當前線程
System.out.println(Thread.currentThread().getName() + " " + j);
if (j == 5) {
TestRunnable tr = new TestRunnable();
// 通過new Thread(Runnable target, String name)方式創建
new Thread(tr, "線程1").start();
new Thread(tr, "線程2").start();
}
}
}
}
運行結果
步驟:
a.創建Callable接口的實現類,實現call()方法,call()方法作為線程執行體,并且有返回值。
b.創建Callable實現類的實例對象,使用FutureTask類來包裝Callable對象。
c.使用FutureTask對象作為Thread對象的target創建并啟動新線程。
d.調用FutureTask對象的get()方法來獲得子線程執行結束后的返回值。
public class CallableTest implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int i = 0;
for (; i < 10; i++) {
// 實現Runnable接口 只能通過Thread.currentThread().getName()獲取線程名稱
System.out.println(Thread.currentThread().getName() + "循環變量 " + i);
}
return i;
}
public static void main(String[] args) {
CallableTest test = new CallableTest();
FutureTask<Integer> ft = new FutureTask<Integer>(test);
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
if (i == 5) {
new Thread(ft, "有返回的線程").start();
}
}
try {
System.out.println("子線程的返回值:" + ft.get());
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//java8支持用Lambda表達式創建Callable對象
public class CallableTest2 {
public static void main(String[] args) {
FutureTask<Integer> ft = new FutureTask<Integer>((Callable<Integer>) () -> {
int i = 0;
for (; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + "循環變量" + i);
}
return i;
});
for (int j = 0; j < 20; j++) {
System.out.println(Thread.currentThread().getName() + " " + j);
if (j == 5) {
new Thread(ft, "有返回值的線程").start();
}
}
try {
System.out.println("子線程的返回值:" + ft.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
運行結果
以上就是關于“Java創建線程的三種方式”的介紹,大家如果想了解更多相關知識,可以關注一下動力節點的Java多線程編程,里面還有更豐富的知識等著大家去學習,希望對大家能夠有所幫助哦。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習