好記性不如爛筆頭77-多線程-Thread子類的線程對象是不同的
阿新 • • 發佈:2017-08-11
function scrip itl 而不是 i++ getname sys imp 不同的
Thread子類的線程對象是不同的。
比方:
EasySelfThread thread = new EasySelfThread();
//同一個線程對象
Thread t1 = new Thread(thread, “t1”);
Thread t2 = new Thread(thread, “==t2”);//(3)
因為t1和t2是兩個對象,所以它們所啟動的線程可同一時候訪問run()函數。
Thread子類的線程對象是不同的java源碼
package com.thread;
/**
* 通過Thread的子類產生的線程對象,是不同對象的線程
*
* @author 範芳銘
*/
public class EasySelfThread implements Runnable {
//public synchronized void print() { // (1)
public void print() { // (1)
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void run() {
this.print();
}
public static void main(String[] args) {
EasySelfThread thread = new EasySelfThread();
//同一個線程對象
Thread t1 = new Thread(thread, "t1" );
Thread t2 = new Thread(thread, "==t2");//(3)
t1.start();
t2.start();
}
}
執行結果
t1 : 0
==t2 : 0
==t2 : 1
t1 : 1
==t2 : 2
t1 : 2
也能夠把run方法用 synchronized 修飾,可是他們還是兩個對象,而不是一個。
好記性不如爛筆頭77-多線程-Thread子類的線程對象是不同的