/**
* 公共的资源(多个线程操作的对象)
*/
public class Info {
private boolean b = false;
private String name = "小白";
private int age = 22;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public synchronized void set(String name, int age) {
if (!b) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.age = age;
b = false;
notifyAll();
}
public synchronized void get() {
if (b) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.getName() + "--" + this.getAge());
b = true;
notifyAll();
}
}
/**
* 生产者
*/
public class Producer implements Runnable {
private Info info = null;
Producer(Info info) {
this.info = info;
}
@Override
public void run() {
boolean b = false;
for (int i = 0; i <= 10; i++) {
if (b) {
this.info.set("小白", 22);
b = false;
} else {
this.info.set("小黑", 66);
b = true;
}
}
}
}
/**
* 消费者
*/
public class Consumer implements Runnable {
private Info info = null;
public Consumer(Info info) {
this.info = info;
}
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.info.get();
}
}
}
测试类
public class TestMain {
public static void main(String[] args) {
Info info = new Info();
Producer pro = new Producer(info);
Consumer con = new Consumer(info);
new Thread(pro).start();
new Thread(con).start();
}
}