空中网面试题二SynchronousQueue

package com.jimmy;


import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AirNet {

public static void main(String[] args) {
//final BlockingQueue bk=new ArrayBlockingQueue(4);
final SynchronousQueue bk=new SynchronousQueue();  //只有有线程等待,才能往队列放数据put
final Lock lk=new ReentrantLock();
System.out.println("begin:"+(System.currentTimeMillis()/1000));


for(int i=0;i<10;i++){  //这行不能改动4

new Thread(new Runnable(){

@Override
public void run() {
while(true){try {
lk.lock();
String str=bk.take();
String output = TestDo.doSome(str);
System.out.println(Thread.currentThread().getName()+ ":" + output);
lk.unlock();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

}).start();



}
for(int i=0;i<10;i++){
String input = i+""; 
try {
bk.put(input);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}



}
}


//不能改动此TestDo类
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;
}
}

你可能感兴趣的:(java)