本帖最后由 yanghao 于 2014-10-5 14:53 编辑
- 如何实现用更短的时间,例如十个线程同时打印,并按照1234的顺序打印
复制代码
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
public class SynchronousQueueTest {
public static void main(String[] args) {
final Semaphore sp=new Semaphore(1);
final BlockingQueue<String> queue=new ArrayBlockingQueue<String>(10);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
public void run() {
while(true){
String out = null;
try {
sp.acquire();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
out = (String)queue.take();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(parsInput(out));
sp.release();
}
}
}).start();
}
for (int i = 0; i < 10; i++) {
String input=""+(i+1);
try {
queue.put(input);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String parsInput(String input){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String output=Thread.currentThread().getName()+input+(System.currentTimeMillis()/1000);
return output;
}
}
|
|