1. 程式人生 > >執行緒使用總結

執行緒使用總結

一. 執行緒基本注意點

(1) Thread的構架函式可接收Runnable及Thread物件。在接收Thread物件時,特別要注意 name屬性

public class Test {
    public static void main(String[] args){
        MyThread thread = new MyThread();
        Thread t1 = new Thread(thread);
        t1.setName("A");
        t1.start();
    }
    
    
    public static
class MyThread extends Thread{ public MyThread(){ System.out.println("Thread.currentThread().getName():"+Thread.currentThread().getName()); System.out.println("this.name:"+this.getName()); } @Override public void run() { System.out.println(
"Thread.currentThread().getName():"+Thread.currentThread().getName()); System.out.println("this.name(run):"+this.getName()); } } }

輸出結果為:

Thread.currentThread().getName():main
this.name:Thread-0
Thread.currentThread().getName():A
this.name(run):Thread-0

我們通常認為輸出第四行應該和第三行一致,其實不然。this.getName() 獲取的是例項物件thread中的屬性值,而在main方法t1.setName(“A”),實際更改的是t1物件的屬性,並未更改thread例項物件的name的屬性;

另外Thread接收了Runnable及Thread例項物件實際上是直接呼叫了2個例項的run方法,因此例項所屬執行緒應該是接收他們的執行緒。