本帖最后由 叶征东 于 2012-8-2 02:32 编辑
class Ticket implements Runnable
{
private int num = 100;
public void run()
{
if (num >0)//你这里没有构成循环,只是一个if语句 。所以三个线程各执行完一次之后就不再会执行了,只输出三次不是因为死锁了,而是因为线程执行完了。还有,将 if (num >0)放在 synchronized外面还是会出现安全问题的,因为(num>0)也涉及到num的运算, 所以应将if (num >0)放在synchronized里面。为了构成循环可以在synchronized外加在上while(true),但需手动停止程序,呵.
{
synchronized(this)
{
{
System.out.println(Thread.currentThread().getName()+"....."+num);
num--;
}
}
}
}
}
class SaleTicket
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
//Thread t4 = new Thread(t);
//Thread t5 = new Thread(t);
t1.start();
t2.start();
t3.start();
//t4.start();
//t5.start();
}
}
我将代码改了,可以参考下。
class Ticket implements Runnable
{
private int num = 100;
public void run()
{
while(true)
{
synchronized(this)
{
if (num >0)
{
System.out.println(Thread.currentThread().getName()+"....."+num);
num--;
}
}
}
}
}
class SaleTicket
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
//Thread t4 = new Thread(t);
//Thread t5 = new Thread(t);
t1.start();
t2.start();
t3.start();
//t4.start();
//t5.start();
}
}
|