ABC三个线程如何保证顺序执行,即顺序打印ABC

最开始因为获取的lockSeq不是最新的,一直没有正确的结果,导致误判notifyAll只会唤醒一个线程,通过对照api,并实际跟踪仔细调试,找到问题。

多线程debug还是很麻烦,step不能看到全局线程状态,通过continue才解决问题。

附上api


Screen Shot 2019-01-12 at 10.16.26 PM.png
public class ThreadSeq {
    public static void main(String args[]) {
        ResourceLock lock = new ResourceLock();
        AThread threadA = new AThread(lock, "A", 0);
        AThread threadB = new AThread(lock, "B", 1);
        AThread threadC = new AThread(lock, "C", 2);

        threadA.start();
        threadB.start();
        threadC.start();
    }
}

class AThread extends Thread {
    public static int THREAD_COUNT = 3;
    private ResourceLock lock;
    private String name;

    private int threadSeq;
    public AThread(ResourceLock lock, String name, int threadSeq) {
        super(name);
        this.lock = lock;
        this.name = name;
        this.threadSeq = threadSeq;
    }

    @Override
    public void run() {

        try {
            synchronized(lock) {
                for (;;) {
                    int lockSeq = lock.getThreadSeq() ;

                    // 这里要注意获取的时候写到while中,写在前面导致是旧的值,浪费了一天的调试时间
                    while (lockSeq != threadSeq) {
                        lock.wait();

                        // 唤醒后获取更新的值
                        lockSeq = lock.getThreadSeq();
                    }

                    System.out.println("------" + name + "------");

                    lockSeq = (lockSeq + 1) % 3;
                    lock.setCurSeq(lockSeq);

                    lock.notifyAll();
                }
            }
        } catch(InterruptedException e) {}

    }
}

class ResourceLock {
    private int curSeq = 0;

    public void setCurSeq(int curSeq) {
        this.curSeq = curSeq;
    }

    public int getThreadSeq() {
        return this.curSeq;
    }
}

你可能感兴趣的:(ABC三个线程如何保证顺序执行,即顺序打印ABC)