大家都看了张老师java5并发库了把,里面空中网面试题第二题的解答如下
张老师代码如下:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.SynchronousQueue;
public class Test {
public static void main(String[] args) throws Exception {
//final BlockingQueue<String> bq = new ArrayBlockingQueue<String>(10);
final SynchronousQueue<String> bq=new SynchronousQueue<String>();
final Semaphore sp = new Semaphore(1,true);
/*Executors.newFixedThreadPool(10).execute(new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
sp.acquire();
String output = null;
output = TestDo.doSome(bq.take());
System.out.println(Thread.currentThread().getName() + ":"
+ output);
sp.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
});*/
for(int i=0;i<10;i++){
new Thread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
try {
sp.acquire();
String output = null;
output = TestDo.doSome(bq.take());
System.out.println(Thread.currentThread().getName() + ":"
+ output);
sp.release();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}).start();
}
System.out.println("begin:" + (System.currentTimeMillis() / 1000));
for (int i = 0; i < 10; i++) { // 这行不能改动
String input = i + ""; // 这行不能改动
bq.put(input);
}
}
}
// 不能改动此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;
}
}//
但是我用线程池改写上面程序却出了问题,也就是开辟一个有10个线程的线程池,来替代用for循环手动开辟10个线程(代码中注释了的部分),但是不知道什么原因线程阻塞了,大家看看问题在哪里。。
|
|