Java面向对象 线程技术 -- 下篇

知识概要:

             (1)线程间的通信           生产者 - 消费者

(2)生产者消费者案例优化

(3)守护线程

(4)停止线程

(5)join

(6)yield与优先级

线程间的通信      生产者 - 消费者

线程间通讯:

           其实就是多个线程在操作同一个资源,但是操作的动作不同。

代码示例

  1. class Res
  2. {
  3. private String name;
  4. private String sex;
  5. private boolean flag = false;
  6.  
  7. public synchronized void set(String name,String sex)
  8. {
  9. if(flag)
  10. try{this.wait();}catch(Exception e){}
  11. this.name = name;
  12.  
  13. this.sex = sex;
  14. flag = true;
  15. this.notify();
  16. }
  17. public synchronized void out()
  18. {
  19. if(!flag)
  20. try{this.wait();}catch(Exception e){}
  21. System.out.println(name+"........"+sex);
  22. flag = false;
  23. this.notify();
  24. }
  25. }
  26.  
  27. class Input implements Runnable
  28. {
  29. private Res r ;
  30. Input(Res r)
  31. {
  32. this.r = r;
  33. }
  34. public void run()
  35. {
  36. int x = 0;
  37. while(true)
  38. {
  39. if(x==0)
  40. r.set("mike","man");
  41. else
  42. r.set("丽丽","女女女女女");
  43. x = (x+1)%2;
  44. }
  45. }
  46. }
  47.  
  48. class Output implements Runnable
  49. {
  50. private Res r ;
  51.  
  52. Output(Res r)
  53. {
  54. this.r = r;
  55. }
  56. public void run()
  57. {
  58. while(true)
  59. {
  60. r.out();
  61. }
  62. }
  63. }
  64.  
  65. class InputOutputDemo2
  66. {
  67. public static void main(String[] args)
  68. {
  69. Res r = new Res();
  70.  
  71. new Thread(new Input(r)).start();
  72. new Thread(new Output(r)).start();
  73. /*
  74. Input in = new Input(r);
  75. Output out = new Output(r);
  76.  
  77. Thread t1 = new Thread(in);
  78. Thread t2 = new Thread(out);
  79.  
  80. t1.start();
  81. t2.start();
  82. */
  83. }
  84. }

生产者消费者案例优化

生产者和消费者共同对同一份资源进行处理,其实质上就是线程的通信。如何更好的处理好线程之间的通信?

  1. import java.util.concurrent.locks.*;
  2.  
  3. class ProducerConsumerDemo2
  4. {
  5. public static void main(String[] args)
  6. {
  7. Resource r = new Resource();
  8.  
  9. Producer pro = new Producer(r);
  10. Consumer con = new Consumer(r);
  11.  
  12. Thread t1 = new Thread(pro);
  13. Thread t2 = new Thread(pro);
  14. Thread t3 = new Thread(con);
  15. Thread t4 = new Thread(con);
  16.  
  17. t1.start();
  18. t2.start();
  19. t3.start();
  20. t4.start();
  21.  
  22. }
  23. }
  24.  
  25. /*
  26. JDK1.5 中提供了多线程升级解决方案。
  27. 将同步Synchronized替换成现实Lock操作。
  28. 将Object中的wait,notify notifyAll,替换了Condition对象。
  29. 该对象可以Lock锁 进行获取。
  30. 该示例中,实现了本方只唤醒对方操作。
  31.  
  32. Lock:替代了Synchronized
  33. lock
  34. unlock
  35. newCondition()
  36.  
  37. Condition:替代了Object wait notify notifyAll
  38. await();
  39. signal();
  40. signalAll();
  41. */
  42. class Resource
  43. {
  44. private String name;
  45. private int count = 1;
  46. private boolean flag = false;
  47. // t1 t2
  48. private Lock lock = new ReentrantLock();
  49.  
  50. private Condition condition_pro = lock.newCondition();
  51. private Condition condition_con = lock.newCondition();
  52.  
  53. public void set(String name)throws InterruptedException
  54. {
  55. lock.lock();
  56. try
  57. {
  58. while(flag)
  59. condition_pro.await();//t1,t2
  60. this.name = name+"--"+count++;
  61.  
  62. System.out.println(Thread.currentThread().getName()+"...生产者.."+this.name);
  63. flag = true;
  64. condition_con.signal();
  65. }
  66. finally
  67. {
  68. lock.unlock();//释放锁的动作一定要执行。
  69. }
  70. }
  71.  
  72. // t3 t4
  73. public void out()throws InterruptedException
  74. {
  75. lock.lock();
  76. try
  77. {
  78. while(!flag)
  79. condition_con.await();
  80. System.out.println(Thread.currentThread().getName()+"...消费者........."+this.name);
  81. flag = false;
  82. condition_pro.signal();
  83. }
  84. finally
  85. {
  86. lock.unlock();
  87. }
  88.  
  89. }
  90. }
  91.  
  92. class Producer implements Runnable
  93. {
  94. private Resource res;
  95.  
  96. Producer(Resource res)
  97. {
  98. this.res = res;
  99. }
  100. public void run()
  101. {
  102. while(true)
  103. {
  104. try
  105. {
  106. res.set("+商品+");
  107. }
  108. catch (InterruptedException e)
  109. {
  110. }
  111.  
  112. }
  113. }
  114. }
  115.  
  116. class Consumer implements Runnable
  117. {
  118. private Resource res;
  119.  
  120. Consumer(Resource res)
  121. {
  122. this.res = res;
  123. }
  124. public void run()
  125. {
  126. while(true)
  127. {
  128. try
  129. {
  130. res.out();
  131. }
  132. catch (InterruptedException e)
  133. {
  134. }
  135. }
  136. }
  137. }

停止线程

stop方法已经过时。

如何停止线程?

      只有一种,run方法结束。

      开启多线程运行,运行代码通常是循环结构。

只要控制住循环,就可以让run方法结束,也就是线程结束。

特殊情况:

当线程处于了冻结状态。

   就不会读取到标记。那么线程就不会结束。

当没有指定的方式让冻结的线程恢复到运行状态是,这时需要对冻结进行清除。

强制让线程恢复到运行状态中来。这样就可以操作标记让线程结束。

Thread类提供该方法 interrupt();

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

守护线程

那Java的守护线程是什么样子的呢。

当JVM中所有的线程都是守护线程的时候,JVM就可以退出了;

如果还有一个或以上的非守护线程则不会退出。    

    

所以setDeamon(true)的唯一意义就是告诉JVM不需要等待这个线程运行结束(退出),当JVM想退出的时候就可以退出吧

join

当A线程执行到了B线程的.join()方法时,A就会等待。等B线程都执行完,A才会执行。

join可以用来临时加入线程执行。

yield:个人理解,就是暂时释放线程,这样线程的执行权就会落到别的线程上。

代码示例

  1. class Demo implements Runnable
  2. {
  3. public void run()
  4. {
  5. for(int x=0; x<70; x++)
  6. {
  7. System.out.println(Thread.currentThread().toString()+"....."+x);
  8. Thread.yield();
  9. }
  10. }
  11. }
  12.  
  13. class JoinDemo
  14. {
  15. public static void main(String[] args) throws Exception
  16. {
  17. Demo d = new Demo();
  18. Thread t1 = new Thread(d);
  19. Thread t2 = new Thread(d);
  20. t1.start();
  21.  
  22. t1.setPriority(Thread.MAX_PRIORITY);
  23.  
  24. t2.start();
  25.  
  26. t1.join();
  27.  
  28. for(int x=0; x<80; x++)
  29. {
  30. System.out.println("main....."+x);
  31. }
  32. System.out.println("over");
  33. }
  34. }

Java面向对象 线程技术 -- 下篇的更多相关文章

  1. Java面向对象 线程技术--上篇

     Java面向对象   线程 知识概要:                   (1)线程与进程 (2)自定义线程的语法结构 (3)多线程概念理解 (4)多线程状态图 (5)多线程--卖票 (6)同 ...

  2. Java——面向对象基础

    Java继承 继承的概念 继承是java面向对象编程技术的一块基石,因为它允许创建分等级层次的类. 继承就是子类继承父类的特征和行为,使得子类具有父类的各种属性和方法,或子类从父类继承方法,使得子类具 ...

  3. Java面向对象(二、继承)

    Java 继承 继承的概念 继承是java面向对象编程技术的一块基石,因为它允许创建分等级层次的类. 继承就是子类继承父类的特征和行为,使得子类对象(实例)具有父类的实例域和方法,或子类从父类继承方法 ...

  4. java面向对象总结(二)

    Java 封装 实现Java封装的步骤 java面向对象值继承 概念: 继承的格式: 类和类之间的关系: 继承的特点: 继承的优缺点 继承的好处: 继承的缺点: 继承的注意事项: 使用继承的步骤: J ...

  5. Java学习笔记二十一:Java面向对象的三大特性之继承

    Java面向对象的三大特性之继承 一:继承的概念: 继承是java面向对象编程技术的一块基石,因为它允许创建分等级层次的类. 继承就是子类继承父类的特征和行为,使得子类对象(实例)具有父类的实例域和方 ...

  6. Java面向对象重要关键字

    面向对象过程接触的重要关键字:extends   super   this   final   static  extends 关键字用作继承功能,可以申明一个类是从另外一个类继承而来的,一般形式如下 ...

  7. 夯实Java基础系列1:Java面向对象三大特性(基础篇)

    本系列文章将整理到我在GitHub上的<Java面试指南>仓库,更多精彩内容请到我的仓库里查看 [https://github.com/h2pl/Java-Tutorial](https: ...

  8. java面向对象(封装,继承,多态,抽象,接口的定义和实现)

    1.封装 在面向对象程式设计方法中,封装(英语:Encapsulation)是指,一种将抽象性函式接口的实作细节部份包装.隐藏起来的方法. 封装可以被认为是一个保护屏障,防止该类的代码和数据被外部类定 ...

  9. Java面向对象OOP思想概述

    目录 OOP思想(Object Oriented Programming) 类和对象 接口 抽象类 OOP三大特性 封装 继承 多态 OOP复用的形式 OOP思想(Object Oriented Pr ...

随机推荐

  1. RAISERROR

    RAISERROR 可以抛出一个错误,并被程序捕获,在存储过程经常使用: 是否进入Catch代码执行区域,在于错误严重等级设置 RAISERROR ('无效数据', 11 , 1) 第一个参数:自定义 ...

  2. 汇编指令-位置无关码(BL)与绝对位置码(LDR)(2)

    位置无关码,即该段代码无论放在内存的哪个地址,都能正确运行.究其原因,是因为代码里没有使用绝对地址,都是相对地址.  位置相关码,即它的地址与代码处于的位置相关,是绝对地址 BL :带链接分支跳转指令 ...

  3. html5中的video标签和audio标签

    不管是否承认,flash早已不像过往那样如日中天了.亚马逊全面放弃flash.苹果放弃flash.安卓也放弃了移动端的flash支持.事实上flash已经不太适合web开发了,因为HTML5中的vid ...

  4. 201521123024 《Java程序设计》第1周学习总结

    一.本周章学习总结 1.Java的版本迁移 2.运用eclipse和notepad++编写Java 3.对JDK,JRE,JVM有初步的了解 二.书面作业 1.为什么java程序可以跨平台运行?执行j ...

  5. Python笔记2.1

    所有类型如下图: 一 基础数据类型 1)数字类型 复制代码 >>> 2/2+2*2 5.0 >>> (50-5*6)/4 5.0 >>> 8/5 ...

  6. 201521123034 《Java程序设计》第9周学习总结

    1. 本周学习总结 1.1 以你喜欢的方式(思维导图或其他)归纳总结异常相关内容. 2. 书面作业 本次PTA作业题集异常 常用异常 题目5-1 1.1 截图你的提交结果(出现学号) 1.2 自己以前 ...

  7. iOS启动图-从网络获取的gif图,在本地一直是没有动画,还模糊的

    背景介绍:APP启动页,常有静态图加链接,gif加链接,短视频等几种形式.我们APP前期只有静态图这一种,功能已经实现.之后,有了添加gif的需求,按理说,只要添加一个类型判断,按照数据类型,通过不同 ...

  8. [js高手之路]Node.js+jade+mongoose实战todolist(分页,ajax编辑,删除)

    该系列文章索引: [js高手之路]node js系列课程-创建简易web服务器与文件读写 [js高手之路]node js系列课程-图解express+supervisor+ejs用法 [js高手之路] ...

  9. org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML doc

    今天在Spring中换了一种配置bean的方式,发现报错了Unexpected exception parsing XML document from class path resource , 经过 ...

  10. JS控制台打印星星,总有你要的那一款~

    用JS语句,在控制台中打印星星,你要的是哪一款呢~来认领吧~ 1.左直角星星 效果: 代码: let readline=require("readline-sync"); cons ...