码迷,mamicode.com
首页 > 编程语言 > 详细

多线程

时间:2016-07-30 16:37:05      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

  public class Test {
    public static void main(String[] args) {
      Message m = new Message();
        new Thread(new SetMessage(m)).start();
        new Thread(new GetMessage(m)).start();
        }
      }

  class Message {
    String name;
    String sex;

  }

  class SetMessage implements Runnable {
    private Message m;

    public SetMessage(Message m) {
    this.m = m;
  }

    int num = 0;

    @Override
      public void run() {
      while (true) {
      synchronized (m) {
      if (num == 0) {
      m.name = "Tom";
      m.sex = "women";
            } else {
        m.name = "Jek";
        m.sex = "men";
    }
}
      num = (num + 1) % 2;
    }
  }

}

  class GetMessage implements Runnable {

    private Message m;

  public GetMessage(Message m) {
    this.m = m;
  }

  @Override
  public void run() {
    while (true) {
      synchronized (m) {
      System.out.println(m.name + "\t" + m.sex);
        }
      }
    }
  }

多线程

标签:

原文地址:http://www.cnblogs.com/striver-lm/p/5720961.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!