关于多线程的问题
1. 关于多线程生产者的职责是什么?
如果共享数据没有被消费,则生产者等消费者消费;生产者被唤醒生产后,要通知消费者
2. 关于多线程消费者的职责是什么?
如果共享数据已没有了,则消费者等待生产者生产,消费者被唤醒消费后,要通知生产者
代码如下:
//PC.java by kakasi in 20160102
import static common.IO.*; //println(xxxx)=System.out.println(xxxx)
//sign
enum State{PUTOVER, GETOVER, UNKNOWN};
//shared data
class Data{
private int count = 0;
private boolean isEmpty = true;
private State state = State.UNKNOWN;
public synchronized void get() throws Exception{
//empty, then wait or return directly
if (isEmpty){
//put is over, return directly
if (state == State.PUTOVER){
state = State.GETOVER;
println("put is over");
println("get is over.");
return;
}
//put is not over, then wait
println("consumer wait.");
wait();
}
//not empty
this.count--; //consume only one every time
if (this.count == 0){
isEmpty = true;
}
println("get() " + 1); //consumer information
println("after get(), remains " + this.count);
notify();
}
public synchronized void put(int count) throws Exception{
//not empty, then wait
if (!isEmpty){
println("producer wait.");
wait();
}
//empty
this.count = count;
if (this.count > 0){
isEmpty = false;
}
println("after put(), remains " + count);
notify();
}
public void setState(State state){
this.state = state;
}
public State getState(){
return state;
}
}
//producer
class Producer implements Runnable{
private Data data;
public Producer(Data data){
this.data = data;
}
public void run(){
for(int i = 1; i < 5; i++){
try{
data.put(i);
}catch(Exception e){}
}
//state = PUTOVER
this.data.setState(State.PUTOVER);
}
}
//consumer
class Consumer implements Runnable{
private Data data;
public Consumer(Data data){
this.data = data;
}
public void run(){
//loop while state != GETOVER
while(this.data.getState() != State.GETOVER){
try{
data.get();
}catch(Exception e){}
}
}
}
//runner
class Test{
public static void main(String[] args) throws Exception{
Data data = new Data();
new Thread(new Producer(data)).start();
new Thread(new Consumer(data)).start();
}
}
结果如下:
转载请注明出处,谢谢!