import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
* 两个线程执行生产
* 两线程执行消费
* 依次交替循环
* lock的方法(类的方法) 针对多线程访问此方法 只允许一个线程执行
* */
public class IntputOutputDome2 {
/**
* @param args
*/
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
public void run() {
int x = 0;
while(true){
if(x==0){
Res2.set("敬先林", "男");
}
else{
Res2.set("张昊", "女");
}
x = (x+1)%2;
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
int x = 0;
while(true){
if(x==0){
Res2.set("敬先林", "男");
}
else{
Res2.set("张昊", "女");
}
x = (x+1)%2;
}
}
});
Thread t3 = new Thread(new Runnable() {
public void run() {
while(true)
Res2.out();
}
});
Thread t4 = new Thread(new Runnable() {
public void run() {
while(true)
Res2.out();
}
});
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Res2{
private static String name;
private static String sex;
private static boolean b = false;
private static Lock lock = new ReentrantLock();
static Condition c1 = lock.newCondition();
static Condition c2 = lock.newCondition();
public static void set(String name1,String sex1){
lock.lock();
try {
while(b){
c1.await();
}
name=name1;
sex=sex1;
System.out.println(Thread.currentThread().getName()+"......生产......"+name+"----"+sex);
b = true;
c2.signal();
} catch (Exception e) {
// TODO: handle exception
}
finally{
lock.unlock();
}
}
public static void out(){
lock.lock();
try {
while(!b){
c2.await();
}
System.out.println(Thread.currentThread().getName()+"......消费................."+name +"----"+sex);
b = false;
c1.signal();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
lock.unlock();
}
}
}