本帖最后由 唐晓 于 2013-1-19 11:11 编辑
需求:有20样东西,有拿走的,也有补货的。在货没有的时候,就不能拿走了,直到补货有了为止
class Res
{
int thing=20;
}
class Input implements Runnable
{
private Res r ;
Input(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
System.out.println(Thread.currentThread().getName()+"...."+ r.thing++);
try{Thread.sleep(10);}
catch(Exception e){}
}
}
}
}
class Output implements Runnable
{
private Res r ;
Output(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
if(r.thing>0)
{
synchronized(r)
{
System.out.println(Thread.currentThread().getName()+"----"+r.thing--);
try{Thread.sleep(10);}
catch(Exception e){}
}
}
}
}
}
class InputOutputDemo
{
public static void main(String[] args)
{
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Output out2 = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
Thread t3 = new Thread(out2);
t1.start();
t2.start();
t3.start();
}
}
运行代码如下:
Thread-0....20
Thread-0....21
Thread-0....22
Thread-0....23
Thread-1----24
Thread-1----23
Thread-2----22
Thread-2----21
Thread-2----20
Thread-1----19
Thread-1----18
Thread-1----17
Thread-0....16
Thread-0....17
Thread-0....18
Thread-1----19
Thread-1----18
Thread-2----17
Thread-1----16
Thread-1----15
Thread-1----14
Thread-1----13
Thread-1----12
Thread-1----11
Thread-0....10
Thread-0....11
Thread-0....12
Thread-0....13
Thread-0....14
Thread-0....15
Thread-1----16
Thread-1----15
Thread-1----14
Thread-1----13
Thread-1----12
Thread-2----11
Thread-2----10
Thread-2----9
Thread-1----8
Thread-1----7
Thread-1----6
Thread-1----5
Thread-1----4
Thread-1----3
Thread-0....2
Thread-0....3
Thread-0....4
Thread-0....5
Thread-0....6
Thread-0....7
Thread-0....8
Thread-0....9
Thread-0....10
Thread-0....11
Thread-1----12
Thread-1----11
Thread-1----10
Thread-1----9
Thread-1----8
Thread-1----7
Thread-1----6
Thread-1----5
Thread-2----4
Thread-2----3
Thread-2----2
Thread-2----1
Thread-1----0
Thread-0....-1
Thread-0....0
Thread-2----1
Thread-1----0
Thread-0....-1
Thread-0....0
怎么会出现-1了呢,取出的时候有判断了如果>0的时候才能-- |