线程问题2(注意实例变量)

 这个例子就是为了说明instance和static变量被多个线程访问的结果:

1.static 的话,肯定要注意多线程的问题
2.instance的话,就看前面caller的代码怎么写了。
  在多个线程的情况下,instance 变量很可能被多个线程修改过。
3.sychronized仅仅是为了保证原子操作性,对变量被多线程访问过是无法控制的

package com.tools.thread.eighth;

public class MultipleThreadTest {
    public static void main(String[] args) {
       
        final Call1 call1 = new Call1();
       
        for (int i = 0; i < 100; i++) {
            Thread  Work = new Thread() {
                public void run() {
                    //下面的注释可以去掉,察看不同的执行结果
                   
//                    call1.synchronous();
                    call1.asynchronous();
//                    call1.call();
                }
            };
           
            Work.start();
        }
       
       
        try {
            Thread.currentThread().sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


package com.tools.thread.eighth;

public class Call1 {
   
    private Call2 call2 = new Call2();
   
    synchronized void synchronous(){
        call2.print();
    }
   
    void asynchronous(){
       
       call2.print();
    }
   
    void call(){
        Call2 call3 = new Call2();
        call3.print();
     }
}


package com.tools.thread.eighth;

public class Call2 {
    private String sharedInstanceResoure = "instanceResource" ;
   
    private static String sharedStaticResouce = "staticResource" ;
   
    public void print(){
        setResource(getResource()+ " "+ Thread.currentThread().getName());       
        System.out.println(Thread.currentThread().getName()+ ":"+getResource());
       
        setStaticResource(getStaticResource()+ " "+ Thread.currentThread().getName());       
        System.out.println(Thread.currentThread().getName()+ ":"+getStaticResource());
    }

    public String getResource() {
        return sharedInstanceResoure;
    }

    public void setResource(String resource) {
        this.sharedInstanceResoure = resource;
    }
   
    public String getStaticResource() {
        return sharedStaticResouce;
    }

    public void setStaticResource(String resource) {
        this.sharedStaticResouce = resource;
    }
   
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值