public static void main(String args[]){
final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(1);
for (int i=0; i<4; i++){
new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
String log = queue.take();
printLog(log);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
for (int i=0; i<16; i++){
final String log = "" + (i+1);
{
try {
queue.put(log);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private static void printLog(String log){
System.out.println(log + ":" + System.currentTimeMillis() / 1000);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出结果是:
1:1358643672
2:1358643672
3:1358643672
4:1358643672
5:1358643673
6:1358643673
7:1358643673
8:1358643673
9:1358643674
10:1358643674
11:1358643674
12:1358643674
13:1358643675
14:1358643675
15:1358643675
16:1358643675