黑马程序员__java基础之线程间通信

来源:互联网 发布:ubuntu 安装类型 编辑:程序博客网 时间:2024/05/01 13:58

------- android培训、java培训、期待与您交流! ----------

线程间通信:

学习思路:
要实现线程间通信,首先要明确的明白通信之间如何连接。也就是说线程之间需要有共享的资源
那如何实现数据共享呢?
实现共享可以有3种方式:
(1)静态;(2)单例设计模式;(3)通过参数传递,这里通过构造函数实现
因为静态存在的时间过长,所以不建议。单例设计模式是允许的,这里的话,我们通过第三种方式进行讲解。

举例如下:

[java] view plaincopyprint?
  1. class ThreadTest
  2. {
  3. public staticvoid main(String[] args)
  4. {
  5. Res r = new Res();
  6. new Thread(new Input(r)).start();
  7. new Thread(new Output(r)).start();
  8. }
  9. }
  10. class Res
  11. {
[java] view plaincopyprint?
  1. /*
  2. 优化前:
  3. String name = name;
  4. String sex = sex;
  5. boolean flag =flag;
  6. */
  7. //优化后
  8. private String name;
  9. private String sex;
  10. private boolean flag =false;
  11. public synchronizedvoid set(String name,String sex)
  12. {
  13. if(this.flag)
  14. try{this.wait();}catch(Exception e){}
  15. this.name = name;
  16. this.sex = sex;
  17. this.flag = true;
  18. try{this.notify();}catch(Exception e){}
  19. }
  20. public synchronizedvoid out()
  21. {
  22. if(!this.flag)
  23. try{this.wait();}catch(Exception e){}
  24. System.out.println(name+"…………"+sex);
  25. this.flag = false;
  26. try{this.notify();}catch(Exception e){}
  27. }
  28. }
  29. class Input implements Runnable
  30. {
  31. private Res r;
  32. Input(Res r)
  33. {
  34. this.r = r;
  35. }
  36. public void run()
  37. {
  38. int x = 0;
  39. while(true)//为了实现连续多次打印,可以开始的用循环的形式进行输出
  40. {
  41. //给变量赋值
  42. /*
  43. 优化前的:
  44. synchronized(r)
  45. {
  46. if(r.flag)
  47. try{r.wait();}catch(Exception e){}
  48. if(x == 0)
  49. {
  50. r.name = "mike";
  51. r.sex = "man";
  52. }
  53. else
  54. {
  55. r.name = "丽丽";
  56. r.sex = "女女女女女";
  57. }
  58. x = (x+1)%2;
  59. r.flag = true;
  60. r.notify();
  61. }
  62. */
  63. //优化后
  64. if(x==0)
  65. r.set("mike","man");
  66. else
  67. r.set("丽丽","女女女女女");
  68. x = (x+1)%2;
  69. }
  70. }
  71. }
  72. class Output implements Runnable
  73. {
  74. private Res r;
  75. Output(Res r)
  76. {
  77. this.r = r;
  78. }
  79. public void run()
  80. {
  81. while(true)
  82. {
  83. //输出结果
  84. /*优化前
  85. synchronized(r)
  86. {
  87. if(!r.flag)
  88. try{r.wait();}catch(Exception e){}
  89. System.out.println(r.name+"…………"+r.sex);
  90. r.flag = false;
  91. try{r.notify();}catch(Exception e){}
  92. }
  93. */
  94. //优化后
  95. r.out();
  96. }
  97. }
  98. }
  99. /*


按上面的输出结果出现"mike 女女女女""丽丽 man"的情况,出现安全问题;
当出现安全问题的时候,首先要分析为什么会这样输出,什么原因呢?显然,这是由于输入输出不同步造成的
即输出的时候还进行到一半的时候,设置的值已经改变。因此,要解决这个问题,我们要做的,就是使
输入输出同步!注意,是输入输出都要同步,而不是其中之一同步。这点要注意。
同步时要注意,为了保证使用同一把锁,要把同步代码块的锁,使用同一对象。这里可以使用r。

完成以上步骤后,就实现了同步。但是有一个问题就是输入输出时总是连续的输出相同的,而我们想要的是:
输入一个,输出一个。为了达到这个目的,我们可以通过使用标记的方式。
开始的时候,我们可以初始化标记为false,如果开始的时候为真,则等待。假的话,就设置值。
当设置完后,标记的flag的真假要改变。顺便说一下,等待多线程放在线程池里,唤醒的时候(notify),
一定要指明唤醒的对象,最先唤醒的,是最近要执行的那一个!任意对象只能被同一对象的锁唤醒。
代码:

因为notify,wai方法哪个都可以调用,所以为Object类型。因为在run方法中,不能抛,只能解决

对程序优化后(见上面优化后代码)

这个线程是输入输出只有一个的情况,而现实中多是多个线程同时运行,这就是生产者消费者问题:

[java] view plaincopyprint?
  1. class ProductConsumerDemo
  2. {
  3. public staticvoid main(String[] args)
  4. {
  5. Resource r = new Resource();
  6. new Thread(new Producer(r)).start();
  7. new Thread(new Producer(r)).start();
  8. new Thread(new Consumer(r)).start();
  9. new Thread(new Consumer(r)).start();
  10. //创建并启动线程
  11. }
  12. }
  13. class Resource
  14. {
  15. private String name;
  16. private int count =1;
  17. private boolean flag;
  18. //生产商品
  19. public synchronizedvoid set(String name)
  20. {
  21. /*
  22. 优化前:
  23. if(flag)
  24. */
  25. //优化后
  26. while(flag)
  27. try{this.wait();}catch(Exception e){}
  28. this.name = name+"--"+count++;
  29. System.out.println(Thread.currentThread().getName()+"生产者-----"+this.name);
  30. flag = true;
  31. /*
  32. 优化前:
  33. try{this.notify();}catch(Exception e){}
  34. */
  35. //优化后:
  36. try{this.notifyAll();}catch(Exception e){}
  37. }
  38. public synchronizedvoid out()
  39. {
  40. /*
  41. 优化前:
  42. if(!flag)
  43. */
  44. //优化后
  45. while(!flag)
  46. try{this.wait();}catch(Exception e){}
  47. System.out.println(Thread.currentThread().getName()+"消费者____________"+this.name);
  48. flag = false;
  49. try{this.notify();}catch(Exception e){}
  50. }
  51. }
  52. //生产者
  53. class Producer implements Runnable
  54. {
  55. private Resource res;
  56. Producer(Resource res)
  57. {
  58. this.res = res;
  59. }
  60. public void run()
  61. {
  62. while(true)
  63. {
  64. res.set("商品");
  65. }
  66. }
  67. }
  68. //消费者
  69. class Consumer implements Runnable
  70. {
  71. private Resource con;
  72. Consumer(Resource con)
  73. {
  74. this.con = con;
  75. }
  76. public void run()
  77. {
  78. while(true)
  79. con.out();
  80. }
  81. }


但是按上面的代码操作时,会出现安全问题。这是因为当多个线程同时运行时,原来的等待唤醒机制出现局限性
因为notify在唤醒的过程中,只唤醒线程池中当前最近要执行的那个线程,如生产者t1,t2,当某一次刚好执行完t1
时,线程t2也处于唤醒状态,而t1在判断完后,刚好处于wait状态,而t2运行后,则不再判断flag的真假性,
这个是引起问题原因之一,如果把if改为while之后,因为notify就出现局限性,导致所有的线程进入等待状态。
要使程序继续执行,则需要用notifyAll方法,改动部分,如下代码:

[java] view plaincopyprint?
  1. //生产商品
  2. public synchronizedvoid set(String name)
  3. {
  4. //优化前:
  5. //if(flag)
  6. //优化后
  7. while(flag)
  8. try{this.wait();}catch(Exception e){}
  9. this.name = name+"--"+count++;
  10. System.out.println(Thread.currentThread().getName()+"生产者-----"+this.name);
  11. flag = true;
  12. //优化前:
  13. //try{this.notify();}catch(Exception e){}
  14. //优化后:
  15. try{this.notifyAll();}catch(Exception e){}
  16. }
  17. public synchronizedvoid out()
  18. {
  19. //优化前:
  20. //if(!flag)
  21. //优化后
  22. while(!flag)
  23. try{this.wait();}catch(Exception e){}
  24. System.out.println(Thread.currentThread().getName()+"消费者____________"+this.name);
  25. flag = false;
  26. try{this.notify();}catch(Exception e){}
  27. }


在这个程序中,notifyAll会同时唤醒本方和对象的线程,那是否可以直接唤醒对方的线程呢?
jdk 5.0之后,对这个问题进行了解决,出现了新的加锁解锁机制。
加锁--解锁:lock---unlock;
对象唤醒机制
condition.await();condition.signal();
将上上述代码转化为升级后的代码为:

[java] view plaincopyprint?
  1. //Jdk 1.5升级后,生产消费者问题
  2. import java.util.concurrent.locks.*;
  3. class ProductConsumerDemo2
  4. {
  5. public static void main(String[] args)
  6. {
  7. Resource r = new Resource();
  8. //创建并启动线程
  9. new Thread(new Producer(r)).start();
  10. new Thread(new Producer(r)).start();
  11. new Thread(new Consumer(r)).start();
  12. new Thread(new Consumer(r)).start();
  13. }
  14. }
  15. class Resource
  16. {
  17. private String name;
  18. private int count =1;
  19. private boolean flag;
  20. //创建使用锁对象
  21. private Lock lock = new ReentrantLock();
  22. private Condition condition_pro = lock.newCondition();
  23. private Condition condition_con = lock.newCondition();
  24. //生产商品
  25. public void set(String name)throws InterruptedException
  26. {
  27. //加锁
  28. lock.lock();
  29. try
  30. {
  31. while(flag)
  32. condition_pro.await();
  33. this.name = name+"--"+count++;
  34. System.out.println(Thread.currentThread().getName()+"生产者---"+this.name);
  35. flag = true;
  36. condition_con.signal();
  37. }
  38. finally
  39. {
  40. lock.unlock(); //解锁
  41. }
  42. }
  43. public void out()throws InterruptedException
  44. {
  45. lock.lock();
  46. try
  47. {
  48. while(!flag)
  49. condition_con.await();
  50. System.out.println(Thread.currentThread().getName()+"消费者-------------"+this.name);
  51. flag = false;
  52. condition_pro.signal();
  53. }
  54. finally
  55. {
  56. lock.unlock(); //解锁
  57. }
  58. }
  59. }
  60. //生产者
  61. class Producer implements Runnable
  62. {
  63. private Resource res;
  64. Producer(Resource res)
  65. {
  66. this.res = res;
  67. }
  68. public void run()
  69. {
  70. while(true)
  71. {
  72. try
  73. {
  74. res.set("商品");
  75. }
  76. catch (InterruptedException e)
  77. {
  78. }
  79. }
  80. }
  81. }
  82. //消费者
  83. class Consumer implements Runnable
  84. {
  85. private Resource con;
  86. Consumer(Resource con)
  87. {
  88. this.con = con;
  89. }
  90. public void run()
  91. {
  92. while(true)
  93. {
  94. try
  95. {
  96. con.out();
  97. }
  98. catch (InterruptedException e)
  99. {
  100. }
  101. }
  102. }
  103. }


jdk1.5版本以后,对锁机制的改正在于使用lock与unlock方法,使加锁解锁更直观;
同时,使用Condition接口子类的方式,在lock接口的子类中可以使用多个Condition接口子类对象,
可以使本方对象唤醒对方。而原来一个同步只能一个对象,多个对象嵌套的话,容易造成死锁。改正后就
避免了这个问题。

在上面对线程操作后,我们都是通过直接在控制台上使用ctrl+c强制结束,那到底该怎么结束运行的线程呢?
在java中只有一种方式,那就是使run中的方法运行结束。结束的关键就是控制循环条件。
如下所示:

[java] view plaincopyprint?
  1. class StopThreadDemo
  2. {
  3. public staticvoid main(String[] args)
  4. {
  5. StopThread t = new StopThread();
  6. Thread t1 = new Thread(t);
  7. Thread t2 = new Thread(t);
  8. t1.start();
  9. t2.start();
  10. int num = 0;
  11. while(true)
  12. {
  13. if(num++ == 60)
  14. {
  15. t.changeFlag();
  16. break;
  17. }
  18. System.out.println(Thread.currentThread().getName()+"………………"+num);
  19. }
  20. }
  21. }
  22. class StopThread implements Runnable
  23. {
  24. private boolean flag =true;
  25. public void run()
  26. {
  27. while(flag)
  28. System.out.println(Thread.currentThread().getName()+"………………Thread run");
  29. }
  30. public void changeFlag()
  31. {
  32. flag = false;
  33. }
  34. }


但是,还有一种情况,就是当多个运行时,如果都处于等待状态,可以使用Thread类的interrupt方法停止
等待状态,使程序继续运行。只是都会抛出异常(注意抛出异常是wait出现异常,而不是中断位置出现
异常),代码如下:

[java] view plaincopyprint?
  1. class StopThreadDemo
  2. {
  3. public staticvoid main(String[] args)
  4. {
  5. StopThread t = new StopThread();
  6. Thread t1 = new Thread(t);
  7. Thread t2 = new Thread(t);
  8. t1.start();
  9. t2.start();
  10. int num = 0;
  11. while(true)
  12. {
  13. if(num++ == 60)
  14. {
  15. //t.changeFlag();
  16. t1.interrupt();
  17. t2.interrupt();
  18. break;
  19. }
  20. System.out.println(Thread.currentThread().getName()+"………………"+num);
  21. }
  22. }
  23. }
  24. class StopThread implements Runnable
  25. {
  26. private boolean flag =true;
  27. public synchronizedvoid run()
  28. {
  29. while(flag)
  30. {
  31. try
  32. {
  33. wait();
  34. }
  35. catch (InterruptedException e)
  36. {
  37. System.out.println(Thread.currentThread().getName()+"………………Exception");
  38. flag = false;
  39. }
  40. System.out.println(Thread.currentThread().getName()+"………………Thread run");
  41. }
  42. }
  43. public void changeFlag()
  44. {
  45. flag = false;
  46. }
  47. }


另外,在多线程中还有这样的方法setDaemo(),守护线程,也可以理解为后台线程。这个线程特点是:
守护的对象结束,这些守护线程也就结束了。如我们可以把上面的interrupt或者同时也把wait取消,
只要把t1,t2,设置为主线程的守护线程,主线程结束,守护线程也就自动停止。

多线程中还有一个join方法,该方法的特点是:直接向cpu索要执行权,如果join在主线程中,那么主线程要
等待该调用join的线程结束,主线程才会执行。
toString在多线程输出有所不同,格式是线程名称,所属线程。setPriority()方法可以设置线程的优先级。
Thread还有yield方法停止当前线程,运行其他线程。

多线程总结(最优选择):
在多线程安全问题控制方面,选择的是lock接口与Condition接口的子类对象,这样可以实现同一把锁,使用
多把锁,因此在唤醒的时候可以直接唤醒对方的线程,在一定程度上也避免了死锁等情况的发生频率。
线程的结束的话,一种方法是通过控制循环条件,让线程自己运行完结束。或者通过"线程名.interrupt()"调用
结束。
此外,还有一种是通过守护线程的形式,当被守护的线程结束,守护线程也就结束了。
如果使用join方法的话,如果在主线程中执行,则必须等调用join的线程执行完,主线程才会执行。
toString方法和setPriority()以及yield方法也是需要注意的对象。

原创粉丝点击