我想了解下面的程序。如果我打電話new ReaderThread().start()
它工作正常,但如果我打電話new ReaderThread().run()
,應用程序進入無限循環。有什麼不同?Java中的線程爭用
public class Contention {
private static boolean ready;
private static int number;
private static class ReaderThread extends Thread {
public void run() {
while (!ready){
System.out.println("ready ..."+ready);
Thread.yield();}
System.out.println(number);
// }
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new ReaderThread().run();
number = 42;
ready = true;
}
}
檢查答案在這裏:http://stackoverflow.com/questions/3027495/java-thread-run-and-start-methods – BenCole