在Java中,創(chuàng)建一個(gè)線程就是創(chuàng)建一個(gè)Thread類(子類)的對(duì)象(實(shí)例)。
Thread類有兩個(gè)常用的構(gòu)造方法:Thread()與Thread(Runnable).對(duì)應(yīng)的創(chuàng)建線程的兩種方式:
● 定義Thread類的子類
● 定義一個(gè)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啟動(dòng)main線程,main線程執(zhí)行main方法");
//3)創(chuàng)建子線程對(duì)象
MyThread thread = new MyThread();
//4)啟動(dòng)線程
thread.start();
/*
調(diào)用線程的start()方法來(lái)啟動(dòng)線程, 啟動(dòng)線程的實(shí)質(zhì)就是請(qǐng)求JVM運(yùn)行相應(yīng)的線程,這個(gè)線程具體在什么時(shí)候運(yùn)行由線程調(diào)度器(Scheduler)決定
注意:
start()方法調(diào)用結(jié)束并不意味著子線程開始運(yùn)行
新開啟的線程會(huì)執(zhí)行run()方法
如果開啟了多個(gè)線程,start()調(diào)用的順序并不一定就是線程啟動(dòng)的順序
多線程運(yùn)行結(jié)果與代碼執(zhí)行順序或調(diào)用順序無(wú)關(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;
/**
* 測(cè)試實(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)類對(duì)象
MyRunnable runnable = new MyRunnable();
//4)創(chuàng)建線程對(duì)象
Thread thread = new Thread(runnable);
//5)開啟線程
thread.start();
//當(dāng)前是main線程
for(int i = 1; i<=1000; i++){
System.out.println( "main==> " + i);
}
//有時(shí)調(diào)用Thread(Runnable)構(gòu)造方法時(shí),實(shí)參也會(huì)傳遞匿名內(nèi)部類對(duì)象
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 1; i<=1000; i++){
System.out.println( "sub ------------------------------> " + i);
}
}
});
thread2.start();
}
}