java多线程顺序打印abc_Java并发编程–三个线程顺序打印ABC | 学步园

three Thread A, B C;

Thread A print "A"

Thread B print "B"

Thread C print "C"

like this ABC...ABC(Total 10 ABC)

代码实现:

/**

*

*/

package concurrent.sample.print;

import java.util.concurrent.atomic.AtomicReference;

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

/**

* three Thread A, B C;

* Thread A print "A"

* Thread B print "B"

* Thread C print "C"

*

* like this ABC...ABC(Total 10 ABC)

*

* 小结:

* 利用lock+cas对简单实现(synchronized+volatile)进行提升性能, 并简化编程

* 使用while(condition) { lock.wait(); }+lockfree

public static void main(String[] args) {

new Thread(new PrintRun(), "A").start();

new Thread(new PrintRun(), "B").start();

new Thread(new PrintRun(), "C").start();

}

/** mutex */

private static final Lock PRINT_LOCK = new ReentrantLock();

/** mutex for waiting print */

private static final Condition PRINT_CONDITION = PRINT_LOCK.newCondition();

/** total print times */

private static final int TOTAL_PRINT_COUNT = 10;

/** semaphore */

private static AtomicReference semaphore = new AtomicReference("A");

public static boolean nextSemaphore() {

boolean result = false;

String semaphoreValue = semaphore.get();

if("A".equals(semaphoreValue)) {

result = semaphore.compareAndSet(semaphoreValue, "B");

} else if("B".equals(semaphoreValue)) {

result = semaphore.compareAndSet(semaphoreValue, "C");

} else if("C".equals(semaphoreValue)) {

result = semaphore.compareAndSet(semaphoreValue, "A");

}

return result;

}

/**

* Thread print current thread name

*/

private static class PrintRun implements Runnable {

/** print times */

private int printCount = TOTAL_PRINT_COUNT;

@Override

public void run() {

while (printCount > 0) {

String threadName = Thread.currentThread().getName();

PRINT_LOCK.lock();

try {

try {

while(!semaphore.get().equals(threadName)) {

PRINT_CONDITION.await();

}

} catch (InterruptedException e) {

System.err.println(threadName + " Print InterruptedException");

PRINT_CONDITION.signalAll();

}

} finally {

PRINT_LOCK.unlock();

}

/* do print */

System.out.print(threadName);

for(;;) {

if (nextSemaphore()) {

break;

}

}

printCount--;

PRINT_LOCK.lock();

try {

PRINT_CONDITION.signalAll();

} finally {

PRINT_LOCK.unlock();

}

}

}

}

}

输出: ABCABCABCABCABCABCABCABCABCABC

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值