线程通讯的优化:
运行效果:
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