本帖最后由 Noword 于 2012-6-25 17:38 编辑
import java.util.concurrent.locks.*;
class Goods
{
private String name;
private int count;
private boolean flag;
private int x;
private Lock lock = new ReentrantLock();
private Condition pro = lock.newCondition();
private Condition con = lock.newCondition();
public void in(String name)
{
lock.lock();
try
{
while (flag)
{
pro.await();
}
this.name = name;
System.out.println(Thread.currentThread()+name+(++count));
flag = true;
con.signal();
}
catch (InterruptedException ie)
{
}
finally
{
lock.unlock();
}
}
public void out()
{
lock.lock();
try
{
while (!flag)
{
con.await();
}
System.out.println(Thread.currentThread()+name+"消费");
flag = false;
pro.signal();
}
catch (InterruptedException ie)
{
}
finally
{
lock.unlock();
}
}
}
class Pro implements Runnable
{
private Goods g;
Pro (Goods g)
{
this.g = g;
}
public void run()
{
while (true)
{
g.in("汽车");
}
}
}
class Con implements Runnable
{
private Goods g;
Con(Goods g)
{
this.g = g;
}
public void run()
{
while (true)
{
g.out();
}
}
}
class day12
{
public static void main(String[] args)
{
Goods g = new Goods();
new Thread(new Pro(g)).start();
new Thread(new Pro(g)).start();
new Thread(new Con(g)).start();
new Thread(new Con(g)).start();
}
}
超级无解的
//编译时错误
运行时错误
|
-
1.png
(12.41 KB, 下载次数: 33)
|