黑马程序员技术交流社区
标题:
while放在synchronized里面和外面的区别
[打印本页]
作者:
l598790586
时间:
2015-5-25 20:33
标题:
while放在synchronized里面和外面的区别
class Ticket implements Runnable//extends Thread
{
private int tick = 300;
Object obj = new Object();
public void run()
{
while (true)
{
synchronized(obj)
{
if(tick>0)
{
try
{
Thread.sleep(5);
System.out.println(Thread.currentThread().getName()+"...sale: "+tick--);
}
catch(Exception e)
{
}
}
}
}
}
}
class ThreadTest3
{
public static void main(String[] args)
{
Ticket t = new Ticket();//这个不是线程
Thread th1 = new Thread(t);
Thread th2 = new Thread(t);
Thread th3 = new Thread(t);
Thread th4 = new Thread(t);
th1.start();
th2.start();
th3.start();
th4.start();
}
}
复制代码
以买票的例子来说,如果把while循环放在synchronized里面,那释放锁的动作要等while循环结束才会做。这样第一个线程开始了,就会直接把票都卖完才会释放锁。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2