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();
}
}
} |
|