爸爸往盘子里放苹果,妈妈往盘子里放桔子,每次只能放一样水果。爸爸放苹果后,叫儿子拿走吃,妈妈放桔子后,叫女儿拿走吃。水果被拿走后,爸爸妈妈又可以往盘子里放水果。利用多线程通信技术编程实现。
import java.util.List;
//爸爸线程
public class Father implements Runnable {
List<String> list;
public Father(List<String> list) {
this.list = list;
}
@Override
public void run() {
while(true){
synchronized (list){
if (list.contains("苹果")){
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println("我正在放苹果,题主快来吃!!");
list.add("苹果");
list.notify();
}
}
}
}
}
import java.util.List;
/*
妈妈线程
*/
public class Mather implements Runnable{
List<String> list;
public Mather(List<String> list) {
this.list = list;
}
@Override
public void run() {
while(true){
synchronized (list){
if (list.contains("桔子")){
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println("妈妈正在放桔子,女儿来拿!!");
list.add("桔子");
list.notify();
}
}
}
}
}
import java.util.List;
/*
儿子线程
*/
public class Son implements Runnable{
List<String> list;
public Son(List<String> list) {
this.list = list;
}
@Override
public void run() {
while(true){
synchronized (list){
if (!list.contains("苹果")){
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println("题主吃完了苹果,答主快来放!!");
list.remove("苹果");
list.notify();
}
}
}
}
}
import java.util.List;
/*
女儿线程
*/
public class Daughter implements Runnable{
List<String> list;
public Daughter(List<String> list) {
this.list = list;
}
@Override
public void run() {
while(true){
synchronized (list){
if (!list.contains("桔子")){
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println("女儿吃完了桔子,妈妈快来放!!");
list.remove("桔子");
list.notify();
}
}
}
}
}
import java.util.ArrayList;
import java.util.List;
/*
测试类
*/
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Thread th1 = new Thread(new Father(list));
th1.start();
Thread th2 = new Thread(new Mather(list));
th2.start();
Thread th3 = new Thread(new Son(list));
th3.start();
Thread th4 = new Thread(new Daughter(list));
th4.start();
}
}
运行效果