所以我寫的程序如下:線程停止,但仍與假布爾值(Java)的運行
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class JustAClass{
private volatile static boolean tof=true;
private static void stop(){
tof=false;
}
private static BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10);
private static void producer() throws InterruptedException{
while(tof){
Random random = new Random();
queue.put(random.nextInt(100));
System.out.println("........");
}
}
private static void consumer() throws InterruptedException{
while(tof){
Random random = new Random();
Thread.sleep(100);
if(random.nextInt(10)==0){
Integer value = queue.take();
System.out.println("Value taken: "+value+"; Queue size: "+queue.size());
}
}
}
public static void main(String[] args) throws InterruptedException{
Scanner scanner = new Scanner(System.in);
System.out.println("Press Enter to terminate");
Thread t1 = new Thread(new Runnable(){
public void run(){
try {
producer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable(){
public void run(){
try {
consumer();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
scanner.nextLine();
stop();
t1.join();
t2.join();
System.out.println("Terminated");
}
}
控制檯通常表明這一點:
Press Enter to terminate
........
........
........
........
........
........
........
........
........
........
........
Value taken: 58; Queue size: 10
Value taken: 53; Queue size: 9
........
Value taken: 9; Queue size: 9
........
的程序必須中止一次我按Enter鍵。雖然輸出停止,但不會顯示消息「終止」。這意味着線程仍然必須運行。我哪裏做錯了? 另外,在某些情況下,顯示消息「Terminated」並且線程停止。爲什麼?
我看不到的方式關閉掃描儀放置在 – Marvin
你代碼可能被阻塞'queue.take()' – assylias
@Marvin在這裏沒有必要 – assylias