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

抢票线程使用同步块修改
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--);

}
}

猜你喜欢

转载自blog.51cto.com/14437184/2429304
今日推荐