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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© kenfine 中级黑马   /  2015-1-14 23:00  /  859 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

今天做了一道程序,主要是线程的之间的同步与通信,之前做过一样的,今天看了一次视频,然后模仿着做,但还是有一点点小细节耽搁了我近一小时,很郁闷自己的逻辑抽象思维那么差。上代码:
  1. class Person{
  2.         private String name;
  3.         private int age;
  4.         private boolean b=true;
  5.         public synchronized void set(String name,int age){
  6.                 if(b)
  7.                         try {
  8.                                 this.wait();
  9.                         } catch (InterruptedException e) {
  10.                                 // TODO 自动生成的 catch 块
  11.                                 e.printStackTrace();
  12.                         }
  13.                 this.name=name;
  14.                 this.age=age;
  15.                 b=true;       
  16.                 this.notify();
  17.         }
  18.         public synchronized void get(){
  19.                 if(!b){
  20.                         try {
  21.                                 this.wait();
  22.                         } catch (InterruptedException e) {
  23.                                 // TODO 自动生成的 catch 块
  24.                                 e.printStackTrace();
  25.                         }
  26.                 }
  27.                 System.out.println("姓名"+this.name+".....年龄"+this.age);
  28.                 b=false;
  29.                 this.notify();
  30.         }
  31. }
  32. class Input implements Runnable{
  33.         private Person p;
  34.         private int x = 0;
  35.         public Input(Person p){
  36.                 this.p=p;
  37.         }
  38.         @Override
  39.         public void run() {
  40.                 while(true){
  41.                                 if(x==0)
  42.                                         p.set("张三", 20);
  43.                                 else
  44.                                         p.set("李四", 30);
  45.                                 x=(x+1)%2;
  46.                 }
  47.         }
  48.        
  49. }
  50. class Output implements Runnable{
  51.         private Person p;
  52.         public Output(Person p){
  53.                 this.p=p;
  54.         }
  55.         @Override
  56.         public void run() {
  57.                 while(true){
  58.                                 p.get();
  59.                 }
  60.         }
  61. }
  62. public class Syn
  63. {
  64.         public static void main(String arg[])
  65.         {       
  66.                 Person p=new Person();
  67.                 new Thread(new Input(p)).start();
  68.                 new Thread(new Output(p)).start();
  69.         }
  70. }
复制代码


其中,18-21,32-34不能用else扩起来,体会了线程是在this.wait();挂起,然后被唤醒是线程从this.wait();后面的语句继续执行,根本不存在if..else逻辑...

1 个回复

倒序浏览
还没有学习到,先暂时过来看看
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马