首页 > 编程语言 > 详细

java 多线程-修改不安全线程2

时间:2019-08-14 11:58:57      阅读:59      评论:0      收藏:0      [点我收藏+]
抢票线程使用同步块修改
synchronized(this){};this锁定的就是这个对象的资源

public class n {

public static void main(String[]args) throws InterruptedException
{
web wb=new web();
new Thread(wb,"a").start();
new Thread(wb,"b").start();
new Thread(wb,"c").start();
}
}

class web implements Runnable{
int num=10;
private boolean flag=true;
public void run()
{
        while(flag)
        {
    test2();
        }
}
//修改同步块
public void test2()
{
    synchronized(this)
    {
if(num<0)
{
    flag=false;
    return;
}
try {
    Thread.sleep(200);
}catch(InterruptedException e)
{
    e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);

}

}

public synchronized void  test()

{   if(num<0)
        {
                flag=false;
    return;
}
try {
    Thread.sleep(200);
}catch(InterruptedException e)
{
    e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+num--);

}
}

java 多线程-修改不安全线程2

原文:https://blog.51cto.com/14437184/2429304

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!