每個線程單獨用於對象的引用變量嗎?
阿新 • • 發佈:2018-04-15
run方法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();
}
}
這段代碼運行結果如下!
事實證明,每個線程對於run方法中的引用都單獨擁有!
註意如果我把node1聲明為類的方法,就不會被線程所單獨擁有!
每個線程單獨用於對象的引用變量嗎?