熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java高級技術 >> 正文

JAVA - 線程之wait(), notify()實例

2022-06-13   來源: Java高級技術 
package introthread;
  
  class Test {
  
  public synchronized void w() {
  
  Systemoutprintln(go into w
  
  try {
  
  wait(
  
  } catch (InterruptedException e) {
  
  // TODO Autogenerated catch block
  
  eprintStackTrace()
  
  }
  
  Systemoutprintln(get out w
  
  notify()
  
  }
  
  public synchronized void n() {
  
  Systemoutprintln(go into n
  
  try {
  
  wait()
  
  } catch (InterruptedException e) {
  
  // TODO Autogenerated catch block
  
  eprintStackTrace()
  
  }
  
  Systemoutprintln(get out n
  
  }
  
  }
  
  class ThreadA extends Thread {
  
  Test t = null;
  
  public ThreadA(Test t) {
  
  thist = t;
  
  }
  
  public void run() {
  
  tw()
  
  }
  
  }
  
  class ThreadA extends Thread {
  
  Test t = null;
  
  public ThreadA(Test t) {
  
  thist = t;
  
  }
  
  public void run() {
  
  tn()
  
  }
  
  }
  
  public class ThreadTest {
  
  public static void main(String[] args) {
  
  Test t = new Test()
  
  ThreadA a = new ThreadA(t)
  
  ThreadA a = new ThreadA(t)
  
  astart()
  
  astart()
  
  }
  
  }
  
  結果
  
  開始輸出
  
  go into w
  
  go into n
  
  過秒後輸出
  
  get out w
  
  get out n
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27364.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.