A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© fmi110 高级黑马   /  2015-9-30 16:01  /  142 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

线程间同通讯主要用于协调线程之间执行顺序,即线程A处理完一件事后,通知B线程处理。也就是说要打破线程之间获取cpu执行权的随机性。要实现这种方法,就需要用查询法,当A或的执行权时,

查询是否该自己运行(用一个变量来指示),不是则进入阻塞状态,并释放执行权。
为了方便实现,线程A B能访问的事同一变量(指示运行的变量),可将线程的执行内容都封装到同一个类中的方法里
在线程里通过run方法来调用该方法,而不是直接将任务代码放到run中
这种设计方法,能更容易实现同步和通讯
  1. package test;


  2. public class Test2 {

  3.         public static void main(String[] args) throws Exception{
  4.                 final P p = new P();
  5.                 new Thread() {
  6.                         public void run() {
  7.                                 for (int i = 1; i < 11; i++) {
  8.                                                 try {
  9.                                                         p.show(i);
  10.                                                 } catch (InterruptedException e) {
  11.                                                         // TODO Auto-generated catch block
  12.                                                         e.printStackTrace();
  13.                                                 }                               
  14.                                 }
  15.                         };
  16.                 }.start();
  17.                 new Thread() {
  18.                         public void run() {
  19.                                 for (int i = 1; i < 11; i++) {
  20.                                         try {
  21.                                                 p.print(i);
  22.                                         } catch (InterruptedException e) {
  23.                                                 // TODO Auto-generated catch block
  24.                                                 e.printStackTrace();
  25.                                         }
  26.                                 }
  27.                         };
  28.                 }.start();
  29.         }
  30. }

  31. class P {
  32.         boolean flag = false;

  33.         public synchronized void show(int i) throws InterruptedException {
  34.                 while (flag)
  35.                         this.wait();
  36.                 System.out.println(i + "..." + Thread.currentThread().getName());
  37.                 flag = true;
  38.                 this.notifyAll();
  39.         }

  40.         public synchronized void print(int i) throws InterruptedException {
  41.                 while (!flag)
  42.                         this.wait();
  43.                 System.out.println(i + "..." + Thread.currentThread().getName());
  44.                 flag = false;
  45.                 this.notifyAll();
  46.         }
  47. }
复制代码


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马