程序说明:
一个读线程,一个写线程, 有一个缓存池资源
写线程写一次到缓存池,读线程读一次输出到控制台。
程序效果:
控制台 交替输出
Jack.....man
静静.....女
....
package test;
class Person {
}
/*
效果:控制台 交替输出
Jack.....man
静静.....女
....
Resouce资源类,flag表示是否为空。
flag = false时只能进行读线程, flag = true是只能进行写线程
set是读线程使用的方法
out是写线程使用的方
Resource类里面的synchronized锁的是Resource类本身
*/
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.name = name;
this.sex = sex;
flag = true;
this.notify();
}
public synchronized void out() {
if (!flag)
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.name + "....." + this.sex);
flag = false;
this.notify();
}
}
class Read implements Runnable {
private Resource res;
Read(Resource res) {
this.res = res;
}
public void run() {
int x = 0;
while (true) {
if (x == 0)
res.set("Jack", "man");
else
res.set("静静", "女");
x = (x + 1) & 1;
}
}
}
class Write implements Runnable {
private Resource res;
Write(Resource res) {
this.res = res;
}
public void run() {
while (true) {
res.out();
}
}
}
public class Test {
public static void main(String[] args) {
Resource res = new Resource();
Read read = new Read(res);
Write write = new Write(res);
Thread rThread = new Thread(read);
Thread wThread = new Thread(write);
rThread.start();
wThread.start();
}
}