黑马程序员技术交流社区
标题:
求告诉指点代码为什么死锁
[打印本页]
作者:
Alan
时间:
2013-5-8 21:20
标题:
求告诉指点代码为什么死锁
本帖最后由 Alan 于 2013-5-9 20:56 编辑
package cn.itcast.io;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PipedDemo {
public static void main(String[] args) throws Exception {
final PipedOutputStream pipeout = new PipedOutputStream();
final PipedInputStream pipein = new PipedInputStream(pipeout);
ExecutorService pool = Executors.newCachedThreadPool();
pool.execute(new Runnable(){
@Override
public void run() {
try {
pipeout.write("hello motou".getBytes());
pipeout.close();
} catch (IOException e) {
throw new RuntimeException("shuchushibai");
}
System.out.println(Thread.currentThread());
}
});
pool.execute(new Runnable(){
@Override
public void run() {
try {
byte[] bit = new byte[1024];
int len = pipein.read(bit);
System.out.println(new String(bit,0,len));
pipein.close();
} catch (IOException e) {
throw new RuntimeException("shurushibai");
}
System.out.println(Thread.currentThread());
}
});
}
}
复制代码
作者:
Jacky_Chen1990
时间:
2013-5-8 21:33
占楼 帮顶
作者:
Super_Class
时间:
2013-5-8 23:42
程序大致是没哟问题的,也没有产生死锁。
进行了一个小的修改,判断是否结束
while(len!=-1)
System.out.println(new String(bit,0,len));
|--你说的应该是程序为什么没有结束吧
因为你创建的是一个ThreadPool也就是所谓的线程池。
需要加pool.shutDown(); 或者pool.shutdownNow();
希望可以帮到你
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2