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