并发趣味问题之ABC

问题描述:
当前三个线程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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值