线程之间的通信

来源:互联网 发布:淘宝美即面膜牛奶白滑 编辑:程序博客网 时间:2024/05/16 09:25

package demo.one;

/**
 *
 * 线程之间的通信其实就是多线程同时操作同一个资源 只是操作的动作不同
 * 线程间的优化
 *
 */
public class ThreadSocketTest {

 /**
  * @param args
  */
 public static void main(String[] args) {

  Person p = new Person();

  Input in = new Input(p);
  Output out = new Output(p);

  Thread t1 = new Thread(in);
  Thread t2 = new Thread(out);

  t1.start();
  t2.start();
 }

}

/**
 *
 * 资源
 *
 */
class Person {
 private String name;
 private String sex;
 private boolean status = false;

 public synchronized void set(String name, String sex) {
  if (status) {
   try {
    this.wait();
   } catch (InterruptedException e) {
   }
  }
  this.name = name;
  this.sex = sex;
  this.status = true;
  notify();
 }

 public synchronized void out() {
  if (!this.status) {
   try {
    this.wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }

  System.out.println(this.name + ".........." + this.sex);
  this.status = false;
  notify();
 }
}

/**
 *
 * 读取资源
 *
 */
class Input implements Runnable {
 private Person p;

 public Input(Person p) {
  this.p = p;
 }

 public void run() {
  int num = 0;
  while (true) {

   
    

     if (num == 0) {
     p.set("jacky", "male"); 
     } else {
      p.set("mexican", "female");
     }
     num=(num+1)%2;
    
    }

   }

  
 }


/**
 *
 * 写入资源
 *
 */
class Output implements Runnable {

 private Person p;

 public Output(Person p) {
  this.p = p;
 }

 public void run() {

  while (true) {
   p.out();
  }
 }
}

原创粉丝点击