多线程——等待-唤醒机制的优化

来源:互联网 发布:pg数据库substring 编辑:程序博客网 时间:2024/05/18 22:13
package com.qianfeng.demo03;/** * 等待唤醒机制的优化 * 代码的优化? * 把同步的代码的操作内容定义在资源当中,比较好,为什么? * 因为更符合面向对象的思想 *  * 把类中的方法设置为由synchronized修饰符修饰,那么他的对象就是线程安全的对象。 *  * 优化步骤: * 1.成员私有化 * 2.提供了set和get的方法。 * 3.把代码当中直接调用属性的过程改为调用方法了。 * *///描述资源的类class Resource3{private String name;private String sex;//设置一个标志位,用来区分输入/输出操作private boolean flag;public synchronized void set(String name,String sex){//判断标志位,如果有数据就说还没输出,当前线程请等待,如果没有数据,就执行当前线程if (flag) {try {     wait();} catch (InterruptedException e) {e.printStackTrace();}}this.name = name;this.sex = sex;//存放数据,更改标记flag = true;this.notify();}public synchronized void out(){if (!flag) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(this.name+".........."+this.sex);//取出数据,更改标志位flag = false;this.notify();}}//如果标志位是true,就去做输出的操作,如果标志位是false,就去做输入操作。//描述输入的任务的类。class Input3 implements Runnable{Resource3 r;//任务一旦初始化就将资源传进来,任务一产生必须有资源public Input3(Resource3 r) {this.r = r;}@Overridepublic void run() {int x = 0;while (true) {if (x==0) {r.set("小红", "女");}else {r.set("小明", "男");}x = (x+1)%2;}}}//描述输出任务的类class Output3 implements Runnable{Resource3 r ;public Output3(Resource3 r) {super();this.r = r;}@Overridepublic void run() {while (true) {r.out();}}}public class ResourceDemo03 {public static void main(String[] args) {//创建资源对象Resource3 r = new Resource3();//创建线程任务对象Input3 input = new Input3(r);Output3 output = new Output3(r);//创建线程对象Thread t1 = new Thread(input);    //输入,存Thread t2 = new Thread(output);   //输出,取//开启线程t1.start();t2.start();}}

0 0