public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
Resou r = new Resou("面包");
Set1 s = new Set1(r);
Get2 g = new Get2(r);
Thread t1 = new Thread(s);
Thread t2 = new Thread(s);
Thread t3 = new Thread(g);
Thread t4 = new Thread(g);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resou {
String name;
int num = 0;
boolean bool = true;
Lock lock = new ReentrantLock();
Condition c1 = lock.newCondition();
Condition c2 = lock.newCondition();
Resou(String name) {
this.name = name;
}
public void getN() {
try {
lock.lock();
while (bool != true)
try {
c1.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("线程名为:" + Thread.currentThread().getName()
+ (num) + "这是生产编号" + "生产的东西为:" + name);
bool = false;
c2.signal();
} finally {
lock.unlock();
}
}
public void setN() {
try {
lock.lock();
try {
c2.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("线程名为:" + Thread.currentThread().getName()
+ (num++) + "这是消费的编号" + "消费的东西为:" + name);
bool = true;
c1.signal();
} finally {
lock.unlock();
}
}
}
class Set1 implements Runnable {
Resou r;
Set1(Resou r) {
this.r = r;
}
public void run() {
while (true) {
r.setN();
}
}
}
class Get2 implements Runnable {
Resou r;
Get2(Resou r) {
this.r = r;
}
public void run() {
while (true) {
r.getN();
}
}
}
你的问题不是很清楚,你是不是想多个线程访问一个段代码? 用jdk5的lock锁机制,不知道是不是,上面是我在你原有的基础上改进的,开启了4个线程,每两个线程为一组访问,你想开启8个线程也是一样可以的,但是效率不高.... |