线程间通讯学习【四】

线程通讯的优化:
package com.zzl.thread;

/**
* 线程间通讯
* 所谓线程间通讯,即多个线程操作同一资源,但是操作的动作不同。
* 线程间通讯的优化 ,把同步锁、wait、notify 封装在资源类中。
*/

class Resource {
private String name;
private String sex;
private boolean flag = false;

public synchronized void set(String name, String sex) {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
this.sex = sex;
flag = true;
this.notify();

}

public synchronized void print() {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name + "========" + sex);
flag = false;
this.notify();

}
}

class InRunnable implements Runnable {
private Resource r;

public InRunnable(Resource r) {
this.r = r;
}

@Override
public void run() {
int x = 0;
while (true) {
if (x == 0) {
r.set("mike", "man");
} else {
r.set("胖胖胖胖胖胖胖胖", "女女女女女女");
}
x = (x + 1) % 2;
}
}

}

class OutRunnable implements Runnable {
private Resource r;

public OutRunnable(Resource r) {
this.r = r;
}

@Override
public void run() {
while (true) {
r.print();
}
}

}

public class ThreadCommunication {
public static void main(String[] args) {
Resource r = new Resource();

InRunnable in = new InRunnable(r);
OutRunnable out = new OutRunnable(r);

Thread t1 = new Thread(in);
Thread t2 = new Thread(out);

t1.start();
t2.start();

}

}


运行效果:
胖胖胖胖胖胖胖胖========女女女女女女
mike========man
胖胖胖胖胖胖胖胖========女女女女女女
mike========man
胖胖胖胖胖胖胖胖========女女女女女女
mike========man
胖胖胖胖胖胖胖胖========女女女女女女
mike========man
胖胖胖胖胖胖胖胖========女女女女女女
mike========man
胖胖胖胖胖胖胖胖========女女女女女女
mike========man
胖胖胖胖胖胖胖胖========女女女女女女
mike========man
胖胖胖胖胖胖胖胖========女女女女女女
mike========man
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值