62,628
社区成员
发帖
与我相关
我的任务
分享
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 (resource.flag)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (x == 0) {
resource.name = "PIG";
resource.sex = "MAN";
} else {
resource.name = "丽丽";
resource.sex = "女";
}
resource.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 (!resource.flag)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ ";刑满释放人员姓名::" + resource.name + ";刑满释放人员性别:"
+ resource.sex);
}
}
}