package heima;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
/*
* 第二题:现成程序中的Test类中的代码在不断地产生数据
* ,然后交给TestDo.doSome()方法去处理,
* 就好像生产者在不断地产生数据,消费者在不断消费数据
* 。请将程序改造成有10个线程来消费生成者产生的数据,
* 这些消费者都调用TestDo.doSome()方法去进行处理,故每个
* 消费者都需要一秒才能处理完,程序应保证这些消费者线程依次有
* 序地消费数据,只有上一个消费者消费完后,下一个消费者才能消费数
* 据,下一个消费者是谁都可以,但要保证这些消费者线程拿到的数
* 据是有顺序的。
*/
public class Test2 {
static Semaphore semaphore = new Semaphore(1);
//这个队列是阻塞操作队列,不同的是,必须一次存一次取
static SynchronousQueue<String> queue = new SynchronousQueue<String>();
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) {
for(int i=0;i<10;i++){
new Thread(new Runnable(){
@Override
public void run() {
String input=null;
try {
semaphore.acquire();
input = queue.take();
System.out.println("take:"+input);
String output = TestDo.doSome(input);
System.out.println(Thread.currentThread().getName()+":"+output);
semaphore.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
/*
* queue队列是说,第一次放的时候,放不进去,一旦有人来取,就放进去,瞬间
* 取走。然后再放的时候仍放不进去,直到再有人来取才能再放进去
* 也可以一下子来一个线程要求取,那就瞬间放进去几个,一个线程取走一个。
*
*/
System.out.println("begin:"+(System.currentTimeMillis()/1000));
for(int i =0;i<10;i++){//这行不能动
String input=i+"";//这行不能改动
try {
queue.put(input);
System.out.println(input+"-");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class TestDo{
public static String doSome(String input){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
String output=input+":"+(System.currentTimeMillis()/1000);
return output;
}
}