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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 小洋人最happy 中级黑马   /  2012-12-9 16:21  /  1213 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*
    第十二天   多线程
   01  线程间通信(示例代码)  02 解决安全问题

无论是售票还是存钱的例子,开启的线程所运行的代码是一致的。
拉煤的例子,一个送,一个拉,同时进行的。动作不一致,运行代码不一致。
所以要有两个run方法来存放数据,放在两个类中。
线程间通讯:就是多个线程操作同一个资源,但是操作的动作不同。
*/
class Rec
{
String name;
String sex;
}
class Input implements Runnable
{
Rec r;
Input(Rec r)
{
  this.r = r;
}
public void run()
{
  int x =0;
  while (true)
  {
   synchronized(r)
   {
    if(x==0)
    {
     r.name = "mike";
     r.sex = "man";
    }
    else
    {
     r.name = "丽丽";
     r.sex = "女女女女女";
    }
    x = (x+1)%2;
   }
  }
}
}
class Output implements Runnable
{
Rec r;
Output(Rec r)
{
  this.r = r;
}
public void run()
{
  synchronized(r)
  {
   System.out.println(r.name+"::::"+r.sex);
  }
}
}
class  ThreadDemo1
{
public static void main(String[] args)
{
  Rec r = new Rec();
  Input in = new Input(r);
  Output out = new Output(r);
  Thread t1 = new Thread(in);
  Thread t2 = new Thread(out);
  t1.start();
  t2.start();
}
}

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 神马都是浮云

查看全部评分

1 个回复

倒序浏览
本帖最后由 张向辉 于 2012-12-9 17:42 编辑

class Rec
{
String name;
String sex;
}
class Input implements Runnable
{
Rec r;
Input(Rec r)
{
  this.r = r;
}
public void run()
{
  int x =0;
  while (true)//老师为了演示,这里用了死循环。。。。。
  {
   synchronized(r)
   {
    if(x==0)
    {
     r.name = "mike";
     r.sex = "man";
    }
    else
    {
     r.name = "丽丽";
     r.sex = "女女女女女";
    }
    x = (x+1)%2;
   }
  }
}
}
class Output implements Runnable
{
Rec r;
Output(Rec r)
{
  this.r = r;
}
public void run()
{
        while(true)//你这里少了这句所以,就打印了一句而已。程序是死循环,而不是死锁!
        {  synchronized(r)
          {
           System.out.println(r.name+"::::"+r.sex);
          }
  }
}
}
class  ThreadDemo1
{
public static void main(String[] args)
{
  Rec r = new Rec();
  Input in = new Input(r);
  Output out = new Output(r);
  Thread t1 = new Thread(in);
  Thread t2 = new Thread(out);
  t1.start();
  t2.start();
}
}
-----------------------------------------------------
你的程序只输出了一句,程序不动了是因为while(true)造成的死循环,而不是死锁,这个程序没有死锁问题!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马