start()與run()方法的區別
start():該方法是在當前線程中啓動一個新的線程,而新啓動的線程會調用run()方法,同時該方法不能重複調用;
run() :該方法和普通的方法一樣,可以重複執行,不會創建新的線程。
1.線程調用得隨機性:
創建一個自定義得線程類MyThread.java,此類繼承自Thread,並且重寫run方法。執行得代碼如下:
/**
* @author renhuifeng
* @program: workThread->MyThread
* @description: 線程的調用得隨機性
* @create: 2019-12-02 14:10
**/
public class MyThread extends Thread{
@Override
public void run(){
super.run();
System.out.println("Mythread");
}
}
class Test{
public static void main(String[] args) {
MyThread th = new MyThread();
th.start();
System.out.println("運行結束!");
}
}
總結:線程的再main方法n次不確定的調用輸出結果得到了變化,證明線程調用時隨機的。
2.演示過線程的調用的隨機性後,演示線程的隨機性
創建自定義線程類MyThread.java,代碼如下:
package com.company;
/**
* @author renhuifeng
* @program: workThread->MyThread
* @description: 線程執行的隨機性
* @create: 2019-12-02 14:10
**/
public class MyThread extends Thread{
@Override
public void run(){
for(int i =0;i<10;i++){
int time = (int) (Math.random()*1000);
try {
Thread.sleep(time);
System.out.println("run=" +Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Test{
public static void main(String[] args) {
MyThread th = new MyThread();
th.setName("myThread");
th.start();
for(int i =0;i<10;i++){
int time = (int) (Math.random()*1000);
try {
Thread.sleep(time);
System.out.println("main=" +Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
在代碼中,爲了展現出線程具有隨機特性,所以使用隨機數的形式來使線程掛起的效果,從而表現出cpu執行哪個線程具有不確定性。
Thread.java 類中的start()方法通知“線程規劃器”此線程已經準備就緒,等待調用線程對象的run()方法。這個過程其實就是讓系統安排一個時間來調用Thread中run()方法,也就是使xain'cehng得到運行,啓動線程,具有異步執行的效果。如果調用代碼thread.run()就不是異步執行了,而是同步,那麼此線程對象並不交給“線程規劃器”來進行處理,而是由main主線程來調用run()方法,也就是必須等run()方法中代碼執行完後纔可以執行後面的代碼。
另外注意是,執行start()方法的順序不代表線程啓動的順序,創建測試代碼如下:
public class MyThread extends Thread{
private int i;
public MyThread(int i) {
this.i = i;
}
@Override
public void run(){
System.out.println(i);
}
}
class Test{
public static void main(String[] args) {
MyThread th1 = new MyThread(1);
MyThread th2 = new MyThread(2);
MyThread th3 = new MyThread(3);
MyThread th4 = new MyThread(4);
MyThread th5 = new MyThread(5);
MyThread th6 = new MyThread(6);
MyThread th7 = new MyThread(7);
MyThread th8 = new MyThread(8);
MyThread th9 = new MyThread(9);
MyThread th10 = new MyThread(10);
th1.start();
th2.start();
th3.start();
th4.start();
th5.start();
th6.start();
th7.start();
th8.start();
th9.start();
th10.start();
}
}
執行結果: