之前写过一篇生产者与消费者的管程法
管程法
对于一些思路可以先看一下这篇博客
什么是信号灯法
我们知道,我们过马路的时候是需要看信号灯的(可能有人不看)当绿灯亮的时候,行人可以走,红灯亮的时候,行人不可以走,车子便可以走了,那么同理,信号灯法就是这个意思,我们需要定一个变量来做信号灯,这里推荐定义Boolean,那么话不多说,我们直接上代码,为了方便大家理解,我们把对象写成,年轻人,老人,年轻人去洗手间方便,方便出来后老人开始打扫卫生间。
代码一览(年轻人)
class youngMan implements Runnable
{
WC wc;//定义一个洗手间类,后面会写
public youngMan(WC wc) {
this.wc = wc;
}
@Override
public void run() {
for (int i = 1; i <= 20; i++) {
if(i%2==0)//设计一个分歧条件
{
try {
this.wc.go_to_WC("大手");//把name传入wc
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else {
try {
this.wc.go_to_WC("小手");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
代码一览(老人)
class oldMan implements Runnable
{
WC wc;
public oldMan(WC wc) {
this.wc = wc;
}
@Override
public void run() {
for(int i=1;i<=20;i++)
{
try {
this.wc.clean_WC();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
代码一览(洗手间)
class WC
{
boolean flag=true;
String name;
public synchronized void go_to_WC(String name) throws InterruptedException {
if(!flag)
{
this.wait();
}
this.name=name;//把name传入
this.flag=!this.flag;
System.out.println("男孩在卫生间--->"+name);
this.notifyAll();
}
public synchronized void clean_WC() throws InterruptedException {
if (flag)
{
this.wait();
}
System.out.println("老人在卫生间清理--->"+name);
this.flag=!this.flag;
this.notifyAll();
}
}
代码总览
package Thread;
public class mytest02 {
public static void main(String[] args) {
WC wc =new WC();
youngMan ymm=new youngMan(wc);
oldMan omm=new oldMan(wc);
Thread t1=new Thread(ymm);
Thread t2=new Thread(omm);
t1.start();
t2.start();
}
}
class oldMan implements Runnable
{
WC wc;
public oldMan(WC wc) {
this.wc = wc;
}
@Override
public void run() {
for(int i=1;i<=10;i++)
{
try {
this.wc.clean_WC();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class youngMan implements Runnable
{
WC wc;
public youngMan(WC wc) {
this.wc = wc;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
if(i%2==0)
{
try {
this.wc.go_to_WC("大手");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else {
try {
this.wc.go_to_WC("小手");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class WC
{
boolean flag=true;
String name;
public synchronized void go_to_WC(String name) throws InterruptedException {
if(!flag)
{
this.wait();
}
this.name=name;
this.flag=!this.flag;
System.out.println("男孩在卫生间--->"+name);
this.notifyAll();
}
public synchronized void clean_WC() throws InterruptedException {
if (flag)
{
this.wait();
}
System.out.println("老人在卫生间清理--->"+name);
this.flag=!this.flag;
this.notifyAll();
}
}
结果
总结
总的来说不是很难理解,只要把向标立好,在加以理解便可,注意的是一定要锁对地方,否则会有错误,如果有不能理解的,建议看一下我上一篇文章,链接在博客顶端,希望我写的可以帮到你。