源码如下:
public class ThreadOfCommunication {
public static void main(String[] args) {
// 创建资源
Resource resource2 = new Resource();
// 创建任务
Input input = new Input(resource2);
Output output = new Output(resource2);
// 创建线程,执行路径
Thread thread1 = new Thread(input);
Thread thread2 = new Thread(output);
// 开启线程
thread1.start();
thread2.start();
}
}
/*
* Resource(资源)
*/
class Resource {
String name;
String sex;
boolean flag=false;
}
/*
* input(输入)
*/
class Input implements Runnable {
Resource resource;
public Input(Resource resource) {
this.resource = resource;
}
public void run() {
int x = 0;
while (true) {
synchronized (resource) {
if(flag)
wait();
if (x == 0) {
resource.name = "PIG";
resource.sex = "MAN";
} else {
resource.name = "丽丽";
resource.sex = "女";
}
flag=true;
notify();
}
x = (x + 1) % 2;
}
}
}
/*
* output(输出)
*/
class Output implements Runnable {
Resource resource;
public Output(Resource resource) {
this.resource = resource;
}
public void run() {
while (true) {// 无限循环所以用while
synchronized (resource) {
if(!flag)
wait();
System.out.println(
Thread.currentThread().getName() + ";刑满释放人员姓名::" + resource.name + ";刑满释放人员性别:" + resource.sex);
}
}
}
}
求解?
忧伤的民工
法球特效
相关分类