黑马程序员技术交流社区
标题:
多线程的问题
[打印本页]
作者:
罗志辉
时间:
2015-10-17 12:52
标题:
多线程的问题
只要一用synchronized,就变成只有一个线程从头卖到尾,试验了数十遍了,怎么解决?
class ThreadDemo3 implements Runnable
{
private int ticket=5000;
String a=new String();
public void run()
{
while(true)
{
synchronized(a)
{
if(ticket>0)
{
try{Thread.sleep(5);} catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"卖出了第"+(5000-(--ticket))+"张票!");
}
}
}
}
}
class ThreadTest3
{
public static void main(String[] args)
{
ThreadDemo3 r=new ThreadDemo3();
Thread t0=new Thread(r,"售票窗口0");
Thread t1=new Thread(r,"售票窗口1");
Thread t2=new Thread(r,"售票窗口2");
Thread t3=new Thread(r,"售票窗口3");
/*
Thread t4=new Thread(new Runnable()
{
private int cola=50;
public void run()
{
while(true)
{
if(cola>0)
{
System.out.println(Thread.currentThread().getName()+"卖出了第"+(50-(--cola))+"杯可乐");
}
}
}
},"可乐窗口");*/
t0.start();
t1.start();
t2.start();
t3.start();
//t4.start();
}
}
复制代码
作者:
tianweidong
时间:
2015-10-17 15:13
我运行了一下正常啊,只是while没有跳出语句,不行的话你把sleep时间改长一点
作者:
lkjmnbqwe
时间:
2015-10-17 22:03
这个好难看懂
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2