[视频]How HandlerThread Wait For Looper

Explanation of Android HandlerThread internal working. Understand the working of the wait method available in the Java Language. MindOrks BootCamp Android doubts resolutions.

--------------------------------WORKER-------------------------------------

package mindorks;

public class Worker extends Thread {

 private Object obj = null;

 @Override
 public void run() {
  super.run();
  try {
   System.out.println("SLEEP: " + Thread.currentThread().getName());
   Thread.sleep(4000);
   System.out.println("AWAKE: " + Thread.currentThread().getName());
   obj = new Object();
   synchronized (this) {
    notifyAll();
   }
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }

 public Object getObject() {

  if (obj != null) return obj;

  synchronized (this) {
   System.out.println("synchronized: " + Thread.currentThread().getName());
   while (obj == null) {
    System.out.println("while: " + Thread.currentThread().getName());
    try {
     wait();
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    System.out.println("wait over: " + Thread.currentThread().getName());
   }
  }
  System.out.println("return: " + Thread.currentThread().getName());
  return obj;
 }
}

--------------------------------APP-------------------------------------

package mindorks;

public class App {

 public static void main(String[] args) {

  Worker worker = new Worker();
  worker.start();
  new Thread(new Runnable() {
   @Override
   public void run() {
    try {
     Thread.sleep(1000);
    } catch (InterruptedException e) {
     e.printStackTrace();
    }
    worker.getObject();
   }
  }).start();
  worker.getObject();

 }
}

--------------------------------OUTPUT-------------------------------

SLEEP: Thread-0
synchronized: main
while: main
synchronized: Thread-1
while: Thread-1
AWAKE: Thread-0
wait over: Thread-1
return: Thread-1
wait over: main
return: main
声明:原创文章,版权所有,转载请注明出处,https://litets.com。