參考的地址:http://www.blogjava.net/xylz/archive/2010/07/30/327582.html
這是空中網技術面試的一個題目。
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
public class synchronouQueue_Thread {
public static void main(String[] args) {
//定義一個Semaphore對象,他就相當於一把鎖一樣。
final Semaphore sema = new Semaphore(1);
//長生一個阻塞的隊列,這個隊列很特殊,當插入一個數據的時候,必須等待另外一個線程進行曲數據操作,當要取數據的時候也要等待另外一個線程插入數據,
//它實現的就是很短的時間內在隊列中存放數據,實際上隊列中是沒有任何一個元素的額、
//當插入一個數據就會立即被另外一個線程取走,後者當取走一個數據後,另外一個線程立即插入數據。
final SynchronousQueue<String> queue = new SynchronousQueue<String>();
for(int i =0;i<10;i++)
{
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
String str;
try {
sema.acquire();
str = queue.take();
String s = test.dosomething(str);
System.out.println(Thread.currentThread().getName()+"--" + s);
sema.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
for(int i=0;i<10;i++)
{
String str = "" + (i+1);
try {
queue.put(str);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class test{
public static String dosomething(String s ){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = s+ " ------ "+ System.currentTimeMillis()/1000;
return str;
}
}