1 System.out.printlnCause the thread to stop

public class ThreadStop { public static boolean stop; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { int i =0; while (! stop) { i++; }}}); thread.start(); TimeUnit.SECONDS.sleep(1); stop = true; }}Copy the code

As we all know, since the stop value is updated on the main thread, the child thread’s value is not up to date, so the loop will continue, but let’s add a line of code and try again

public class ThreadStop { public static boolean stop; public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Runnable() { @Override public void run() { int i =0; while (! stop) { i++; System.out.println(" I "+ I); }}}); thread.start(); TimeUnit.SECONDS.sleep(1); stop = true; }}Copy the code

We’ll notice that the thread has stopped. What? Println contains the synchronized keyword, which changes the value of stop. The Jvm CPU does its best to ensure that the value of stop is updated, but it is not 100% successful. If the CPU is not free, it must do its best. It will not be updated, but once the CPU is free, it will have a chance to update. So the key is to let the CPU get the time slice, and we can also do sleep in a while, and we can also do thread termination

2 How to Understandsleepwait

Let’s start with a few questions: 1. Does sleep give up a thread-owned lock? 2. Do I need to hold the lock before I call wait? If necessary, does nameWait relinquish the lock on the object’s possession after it?

2.1 Wait Pool and Lock Pool

Let’s start with two concepts

  • Lock pool: When multiple threads compete for an objectAasynchronizedMethod, only one thread will hold the lock, and all the other threads will have to wait, at which point the waiting thread will enter object ALock pool
  • Waiting for the pool: If threadTCalled the threadAwaitMethod,TThe lock on the object is released and the object is enteredAWait pool, if any other objectnotifyornotifyAllCalled, the name objectAWait pool (1 or all, depending onnotifyornotifyAll) will enter the lock pool and fight for ownership of the lock

So the initial answer is 1. Sleep does not give up the lock, even if sleep still holds 2. An exception is raised if a thread that has not held a lock calls the wait method on an object. If a thread that has not held a lock calls the wait method on an object, an exception is raised