为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Java

         

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

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
数据库工程师
手记
粉丝
52
获赞与收藏
361

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消