我有2個版本:主要和線程2。醒來從的readLine(線程)(從System.in,無插座)
主要 - >創建Thread2,睡3秒,退出。
Thread2 - > readline from System.in並退出。
我想喚醒線程2,如果它是在readline()中的塊,我不想使用超時,並且通過在Thread2中生成異常來關閉主輸入流不起作用。
的代碼:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
public class Main {
public static void main(String[] args) throws InterruptedException {
InputStreamReader sc = new InputStreamReader(System.in);
Thread2 t = new Thread2(sc);
Thread tt = new Thread(t);
tt.start();
Thread.sleep(3000);
System.out.println("exit sleep");
tt.interrupt();
System.out.println("exit main");
}
}
class Thread2 implements Runnable {
InputStreamReader qst;
public Thread2(InputStreamReader sc) {
qst = sc;
}
public void run() {
BufferedReader buff = new BufferedReader(qst);
try {
System.out.println("read thread");
buff.readLine(); //Here is locked!!!!!!!!!!!!!!!!!!
} catch (InterruptedIOException e) {
System.out.println("exit thread");
} catch (IOException e) {
e.printStackTrace();
}
}
}
執行(的println):
- 讀取線程
(後3秒)
-exit睡眠
-exit main
但是,線程2不停止 - >它是在readline中的塊。爲什麼?
感謝這項工作! – John