Thread contention in Java
•
Java
I want to know the following procedure If I call new readerthread() Start() it works normally, but if I call new readerthread() Run (), the application will enter an infinite loop Any difference?
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; } }
Solution
If you use the new readerthread() start();, You actually create a new thread instance that will run in the background and main () will continue to execute
But the new readerthread() run(); Create an instance of this class and make regular method calls to the run () method, so main () must wait until run () completes execution and returns control to main (), which is an infinite loop in your case
If you want to start a new thread, use readerthread() start(); This is the correct way to start a thread. There is no alternative
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码