我有2個主題,其中一個輪詢郵箱中的郵件,然後正在睡覺while (!quit)
,另一個應該更改quit
標誌,如果用戶輸入'Q'
。似乎掃描線程阻塞其他線程執行,直到有一些輸入(通常是2行)。我試着改變線程的優先級和它們開始的順序,但都無濟於事。如何讓我的主題不會彼此阻塞?
class quitThread extends Thread {
public void run() {
char c;
Scanner scanner = new Scanner(System.in);
do {
c = scanner.nextLine().toUpperCase().charAt(0);
} while (c != 'Q');
quit = true;
}
}
class recieveThread extends Thread {
public void run() {
System.out.println("thread started");
while (!quit) {
try {
MailHandler handler = new MailHandler();
handler.recieve();
System.out.println("Sleeping");
sleep(_sleepinterval);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
我知道我擔心互斥和同步的,但我想在線程至少工作之前,我開始擔心。 編輯: 這是我怎樣,我開始線程:
void go() throws Exception{
char c;
System.out.println("S or R");
Scanner s = new Scanner(System.in);
c = s.nextLine().toUpperCase().charAt(0);
MailHandler handler = new MailHandler();
QuitThread q = new QuitThread();
q.setPriority(java.lang.Thread.MIN_PRIORITY);
RecieveThread rc = new RecieveThread();
rc.setPriority(java.lang.Thread.MAX_PRIORITY);
switch (c){
case 'S':
handler.send("[email protected]", "hello there");
break;
case 'R':
rc.start();
q.start();
break;
default :
break;
}
}
注:優先事項是不是原來在那裏,它的東西,我只是想和它沒有任何區別。
代碼片段中沒有明顯的問題。沒有足夠的信息來推斷問題的原因。 – McDowell 2009-02-25 15:17:31
你需要展示你如何開始這些線程。 – Clint 2009-02-25 15:38:44
我希望「quit」被定義爲volatile。你現在確實需要擔心同步。這可能是你的問題的一部分。另外,在Java中,類名預計以大寫字母開頭。 – Eddie 2009-02-25 15:46:39