在Java中,創建一個線程就是創建一個Thread類(子類)的對象(實例)。
Thread類有兩個常用的構造方法:Thread()與Thread(Runnable).對應的創建線程的兩種方式:
● 定義Thread類的子類
● 定義一個Runnable接口的實現類
這兩種創建線程的方式沒有本質的區別。
package com.wkcto.createthread.p1;
/**
* 1)定義類繼承Thread
* Author : 蛙課網老崔
*/
public class MyThread extends Thread{
//2) 重寫Thread父類中的run()
//run()方法體中的代碼就是子線程要執行的任務
@Override
public void run() {
System.out.println("這是子線程打印的內容");
}
}
package com.wkcto.createthread.p1;
/**
* Author : 蛙課網老崔
*/
public class Test {
public static void main(String[] args) {
System.out.println("JVM啟動main線程,main線程執行main方法");
//3)創建子線程對象
MyThread thread = new MyThread();
//4)啟動線程
thread.start();
/*
調用線程的start()方法來啟動線程, 啟動線程的實質就是請求JVM運行相應的線程,這個線程具體在什么時候運行由線程調度器(Scheduler)決定
注意:
start()方法調用結束并不意味著子線程開始運行
新開啟的線程會執行run()方法
如果開啟了多個線程,start()調用的順序并不一定就是線程啟動的順序
多線程運行結果與代碼執行順序或調用順序無關
*/
System.out.println("main線程后面其他 的代碼...");
}
}
package com.wkcto.createthread.p3;
/**
* 當線程類已經有父類了,就不能用繼承Thread類的形式創建線程,可以使用實現Runnable接口的形式
* 1)定義類實現Runnable接口
* Author : 蛙課網老崔
*/
public class MyRunnable implements Runnable {
//2)重寫Runnable接口中的抽象方法run(), run()方法就是子線程要執行的代碼
@Override
public void run() {
for(int i = 1; i<=1000; i++){
System.out.println( "sub thread --> " + i);
}
}
}
package com.wkcto.createthread.p3;
/**
* 測試實現Runnable接口的形式創建線程
* Author : 蛙課網老崔
*/
public class Test {
public static void main(String[] args) {
//3)創建Runnable接口的實現類對象
MyRunnable runnable = new MyRunnable();
//4)創建線程對象
Thread thread = new Thread(runnable);
//5)開啟線程
thread.start();
//當前是main線程
for(int i = 1; i<=1000; i++){
System.out.println( "main==> " + i);
}
//有時調用Thread(Runnable)構造方法時,實參也會傳遞匿名內部類對象
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 1; i<=1000; i++){
System.out.println( "sub ------------------------------> " + i);
}
}
});
thread2.start();
}
}