黑马程序员技术交流社区
标题:
为什么只运行了一次呢?
[打印本页]
作者:
凌风未动
时间:
2016-7-19 09:07
标题:
为什么只运行了一次呢?
class ThreadDemo2
{
public static void main(String[] args) throws Exception
{
Tick t=new Tick();
Con1 con1=new Con1(t);
Con2 con2=new Con2(t);
Thread t1=new Thread(con1,"消费者1");
Thread t2=new Thread(con2,"消费者2");
t1.start();
t2.start();
}
}
class Tick
{
private int tickNum=100;
private Object obj=new Object();
int x=0;
public void sell()
{
synchronized(obj)
{
try
{
if(x%2==0)
{
if(tickNum>0)
System.out.println(Thread.currentThread().getName()+":::"+tickNum--);
x=x+1;
}
}
catch (Exception e)
{
e.printStackTrace(System.out);
}
}
}
}
class Con1 implements Runnable
{
Tick t;
Con1(Tick t)
{
this.t=t;
}
public void run()
{
while(true)
{
if(t.x%2==0)
t.sell();
}
}
}
class Con2 implements Runnable
{
Tick t;
Con2(Tick t)
{
this.t=t;
}
public void run()
{
while(true)
{
if(t.x%2!=0)
t.sell();
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2