并发趣味问题之ABC

来源:互联网 发布:新网互联域名如何续费 编辑:程序博客网 时间:2024/06/06 00:25

问题描述:
当前三个线程A,B,C,三个成一组,总共执行10次。第一次执行的时候按照ABC的顺序执行,以后每组按照A–>B–>C–>A的回环顺序执行即可(即若开始为B那么之后就是C,接着是A;若开始是C那接着就是A,之后是B)。

我自己的实现方式,欢迎拍砖。

线程类

package gu;public class Father extends Thread{    private String myState;    private String nextState;    private Source source;    public Source getSource()    {        return source;    }    public void setSource(Source source)    {        this.source = source;    }    public String getMyState()    {        return myState;    }    public void setMyState(String myState)    {        this.myState = myState;    }    public String getNextState()    {        return nextState;    }    public void setNextState(String nextState)    {        this.nextState = nextState;    }    public Father(String myState, String nextState, Source source)    {        this.myState = myState;        this.nextState = nextState;        this.source = source;    }    @Override    public void run()    {        source.show(this);    }}

虚拟资源类

package gu;public class Source{    private String state = "A";    private int count = 0;    public String getState()    {        return state;    }    public void setState(String state)    {        this.state = state;    }    public synchronized void show(Father father)    {        if (count % 3 == 0 && count != 0)        {            setState(father.getMyState());        }        if (!this.state.equals(father.getMyState()))        {            try            {                notifyAll();                wait();                show(father);            }            catch (InterruptedException e)            {                e.printStackTrace();            }        }        else        {            System.out.print(father.getMyState());            setState(father.getNextState());            count++ ;            notifyAll();            if (count % 3 == 0 && count != 0)            {                System.out.println();            }        }    }}

测试类

package gu;public class Test{    public static void main(String[] args)    {        Source source = new Source();        for (int i = 0; i < 10; i++ )        {            Father a = new Father("A", "B", source);            Father b = new Father("B", "C", source);            Father c = new Father("C", "A", source);            a.start();            b.start();            c.start();        }    }}
0 0