手记

每个线程单独用于对象的引用变量吗?

         

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声明为类的方法,就不会被线程所单独拥有!

0人推荐
随时随地看视频
慕课网APP