two ways of multiThread


//public class TestThread extends Thread{
public class TestThread implements Runnable{
// private static Object lock = new Object();
 @SuppressWarnings("static-access")
 public void run() {

  System.out.println("new thread is running");
//  synchronized (lock) {
  synchronized (Thread.currentThread()) {
   try {
    System.out.println("The thread is waiting");
    //lock.wait();
    //Thread.currentThread().sleep(400);
    Thread.currentThread().wait(400);
    System.out.println("The thread is unwait");
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 @SuppressWarnings("static-access")
 public static void main(String[] args) {
  //TestThread t1 = new TestThread();
  Thread t1 = new Thread(new TestThread());
  try {
   t1.start();
   System.out.println("main is running");
   System.out.println("main is sleeping");
   Thread.currentThread().sleep(500);
   System.out.println("main is unsleep");
//   synchronized (lock) {
//    lock.notifyAll();
//   }
   synchronized (Thread.currentThread()) {
    Thread.currentThread().notifyAll();
   }
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章