每個線程單獨用於對象的引用變量嗎?

package Thread;

import org.omg.PortableServer.THREAD_POLICY_ID;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class node{
    public int num;
    node(int nums){
        num=nums;
    }
    public node next;

}
class myTest implements Runnable{
    String s=null;
    node n1=new node(1);
    node n2=new node(2);
    node n3=new node(3);

    @Override
    public void run() {

        n1.next=n2;
        n2.next=n3;
        n3.next=null;

        node e=n1;

        while(e!=null){
            node n1=e.next;
            System.out.println("當前線程爲"+Thread.currentThread().getName());
            if(Thread.currentThread().getName().equals("Thread-0")){
                try {
                    System.out.println("Thread-0要阻塞了");
                    Thread.sleep(10000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                if(e==null){
                    System.out.println("e在線程中不在單獨擁有");
                }
                else {
                    System.out.println("單獨擁有");
                    System.out.println(e.num);
                }
            }
            System.out.println(Thread.currentThread().getName()+"+++"+e.num);

            e=e.next;
            if(e==null){
                System.out.println("在"+Thread.currentThread().getName()+"中e已經爲空了");
            }
        }


    }
}
public class Test1 {
    public static void main(String[] args) {
        myTest myTest=new myTest();
        Thread t1=new Thread(myTest);
        Thread t2=new Thread(myTest);
        t1.start();
        t2.start();
    }
}

這段代碼運行結果如下!


blob.png



事實證明,每個線程對於run方法中的引用都單獨擁有!

注意如果我把node1聲明爲類的方法,就不會被線程所單獨擁有!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章