JAVA多线程变量的深入认识(二)

接下来,我们对类TestInstance换一种访问方式:    
例II:    
(1)我们把类TestInstance的两个实例分别放在不同的线程当中    
public class ForSynchronizedTwo {    
    public static void main(String ars[])throws IOException    
    {     
        RunInstance t = new RunInstance();     
        RunInstance y = new RunInstance();     
        Thread t1 = new Thread(t);     
        Thread y1 = new Thread(y);     
        t1.start();     
        y1.start();    
        }    
    }    
class RunInstance implements Runnable{    
    TestInstance theinstance=new TestInstance();    
    public void run(){    
        theinstance.runtest();    
        }    
}    
(2)结果我们发现,两个线程用的都是m1这个方法,因为这时flag是个局部变量,它被创建了两次,    
且并不会被线程互相访问,但是count 则不然,它是全局(严格说是static )变量,并且用了synchronized进行同步访问。    
另外,请注意count = 2被打印两次,是因为Thread-0实行了 count++后,CPU等待Thread-1实行 count++    
的结果。    
Thread-0: m1's printing : count = 2    
Thread-1: m1's printing : count = 2    
Thread-0: m1's printing : count = 3    
Thread-1: m1's printing : count = 4    
Thread-0: m1's printing : count = 5    
Thread-1: m1's printing : count = 6    
Thread-0: m1's printing : count = 7    
Thread-1: m1's printing : count = 8    
Thread-0: m1's printing : count = 9    
Thread-1: m1's printing : count = 10    
Thread-0: m1's printing : count = 11    
Thread-0: m1's printing : count = 13    
Thread-1: m1's printing : count = 13    
Thread-0: m1's printing : count = 14    
Thread-1: m1's printing : count = 15    
Thread-0: m1's printing : count = 16    
Thread-1: m1's printing : count = 17    
Thread-0: m1's printing : count = 18    
Thread-1: m1's printing : count = 19    
Thread-1: m1's printing : count = 20    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值