import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test {
public static void main(String[] args) {
Resource r = new Resource();
Input input = new Input(r);
Output output = new Output(r);
new Thread(input).start();
new Thread(input).start();
new Thread(output).start();
new Thread(output).start();
}
}
/**
两个线程共同的资源
@author WangShuang
*/
class Resource{
private String name;
private String sex;
private int count;
private boolean flag;//添加一个标记用来表示Resource中的资源是否为空(Input以后代表存入不为空,Output以后代表取出为空)
Lock lock = new ReentrantLock();
Condition condition_input = lock.newCondition();
Condition condition_output = lock.newCondition();
public String getOutput() {
lock.lock();//上锁
while(flag){//如果flag是真,代码资源库中的资源还没有被取走,此时该线程应该放弃cpu的执行权,并把另一个线程叫醒
try {condition_input.await();} catch (InterruptedException e) {e.printStackTrace();}
}
System.out.println(Thread.currentThread().getName()+"消费了一个"+sex+"---------------"+name);
flag=true;
condition_output.signal();
lock.unlock();//开锁
return name+"---"+sex;}
public void setInput(String name,String sex) {
lock.lock();//上锁
while(!flag){//如果flag是假,代码资源库中的资源已经被取走,此时该线程应该放弃cpu的执行权,并把另一个线程叫醒
try {condition_output.await();} catch (InterruptedException e) {e.printStackTrace();}
}
this.name = name+count++;
this.sex = sex;
System.out.println(Thread.currentThread().getName()+"生产了一个"+this.sex+"---"+this.name);
flag=false;
condition_input.signal();
lock.unlock();//开锁
}
}
/**
存资源的线程
@author WangShuang
*/
class Input implements Runnable {
private Resource resource;
public Input(Resource resource) {this.resource=resource;
}
@Overridethis.resource=resource;
}
@Override
this.resource=resource;
}
@Override
br/>this.resource=resource;
}
@Override<br <="" a="">public void run() {
while(true){
resource.getOutput();
}
}
}
this.resource=resource;
}
@Override
this.resource=resource;
}
@Override
共同学习,写下你的评论
评论加载中...
作者其他优质文章