Chinaunix首页 | 论坛 | 博客
  • 博客访问: 741110
  • 博文数量: 130
  • 博客积分: 2951
  • 博客等级: 少校
  • 技术积分: 1875
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-04 18:32
文章分类

全部博文(130)

文章存档

2013年(1)

2012年(129)

分类: Java

2012-03-29 19:32:13


点击(此处)折叠或打开

  1. package intro.thread;

  2. class Test {
  3.     public synchronized void w() {
  4.         System.out.println("go into w");
  5.         try {
  6.             wait(5000);
  7.         } catch (InterruptedException e) {
  8.             // TODO Auto-generated catch block
  9.             e.printStackTrace();
  10.         }
  11.         System.out.println("get out w");
  12.         notify();
  13.     }

  14.     public synchronized void n() {
  15.         System.out.println("go into n");
  16.         try {
  17.             wait();
  18.         } catch (InterruptedException e) {
  19.             // TODO Auto-generated catch block
  20.             e.printStackTrace();
  21.         }
  22.         System.out.println("get out n");
  23.     }
  24. }

  25. class ThreadA3 extends Thread {
  26.     Test t = null;

  27.     public ThreadA3(Test t) {
  28.         this.t = t;
  29.     }

  30.     public void run() {
  31.         t.w();
  32.     }
  33. }

  34. class ThreadA4 extends Thread {
  35.     Test t = null;

  36.     public ThreadA4(Test t) {
  37.         this.t = t;
  38.     }

  39.     public void run() {
  40.         t.n();
  41.     }
  42. }

  43. public class ThreadTest3 {
  44.     public static void main(String[] args) {
  45.         Test t = new Test();
  46.         ThreadA3 a3 = new ThreadA3(t);
  47.         ThreadA4 a4 = new ThreadA4(t);
  48.         a3.start();
  49.         a4.start();
  50.     }
  51. }
结果:
开始输出
go into w
go into n
过5秒后输出
get out w
get out n


阅读(1594) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~