黑马程序员技术交流社区
标题:
多线程同步问题
[打印本页]
作者:
ring8677
时间:
2015-5-20 20:22
标题:
多线程同步问题
看一下这段代码,为什么每次运行时都是0线程在走而其他线程都不走呢?
class ThreadDemo4
{
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);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Ticket implements Runnable
{
private int num = 1000;
Object obj = new Object();
public void run()
{
show();
}
public void show()
{
while (true)
{
synchronized(obj)
{
if (num>0)
{
try
{
Thread.sleep(20);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("线程名字:"+Thread.currentThread().getName()+"--num:"+ num--);
}
}
}
}
}
复制代码
作者:
马也keyboard
时间:
2015-5-28 10:49
我运行了下代码,所有的线程都在跑啊。
哥们你是不是运行错class文件了
作者:
途中ms前进
时间:
2015-5-28 11:05
路过看看
作者:
ring8677
时间:
2015-5-30 15:14
马也keyboard 发表于 2015-5-28 10:49
我运行了下代码,所有的线程都在跑啊。
哥们你是不是运行错class文件了
没有,后来我也运行了,也是所有线程都在跑,原因可能就是偶然性导致的。
作者:
zhousuo28
时间:
2015-5-30 21:08
偶然性吧,睡眠时间长点试试看?
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2