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

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

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

附上api

cf25a7e20a00

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值