您的位置:首页 > 其它

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

2016-08-20 11:20 288 查看
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;
}

@Override
public 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;
}

@Override
public 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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多线程