Java多线程循环打印ABC等问题(三种方式)

private static final Integer MAX_COUNT = 6;

private static String[] chars = {“a”, “b”, “c”};

private String name;

public AtomicIntegerThread(String name,AtomicInteger currentCount) {

this.name = name;

this.currentCount = currentCount;

}

@Override

public void run() {

while (currentCount.get() < MAX_COUNT) {

if (this.name.equals(chars[currentCount.get() % 3])) {

printAndPlusOne(this.name);

}

}

}

public void printAndPlusOne(String content) {

System.out.print(content);

currentCount.getAndIncrement();

}

public static void main(String[] args) {

AtomicInteger currentCount = new AtomicInteger(0);

ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 3, 20, TimeUnit.MINUTES, new LinkedBlockingQueue());

threadPoolExecutor.execute(new AtomicIntegerThread(“a”,currentCount));

threadPoolExecutor.execute(new AtomicIntegerThread(“b”,currentCount));

threadPoolExecutor.execute(new AtomicIntegerThread(“c”,currentCount));

threadPoolExecutor.shutdown();

}

}

这里一定要注意有一个坑,如果线程池核心线程数少于3个,1个或者2个,上述代码会有问题,因为线程池的队列是无界队列,多余核心线程数的任务会

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java线程每个线程挨着打印abc的4种实现方式如下: 1. 使用同步方法: 在一个类中创建一个共享的锁对象。创建3个线程,分别调用该对象的3个同步方法,在每个方法中使用循环打印对应的字符,然后调用notifyAll()方法唤醒其他两个线程,最后调用wait()方法当前线程进入等待状态。 2. 使用synchronized关键字: 在一个类中创建一个共享的锁对象,并使用synchronized关键字修饰方法。创建3个线程,分别调用该对象的3个同步方法,在每个方法中使用循环打印对应的字符,然后调用notifyAll()方法唤醒其他两个线程,最后调用wait()方法当前线程进入等待状态。 3. 使用Lock和Condition接口: 创建一个ReentrantLock对象和3个Condition对象。创建3个线程,分别获取对应的Condition对象,然后在循环中使用Lock对象的lock()方法获取锁,使用对应的Condition对象的await()方法等待,直到该线程被唤醒后打印对应的字符,并调用其他两个Condition对象的signalAll()方法唤醒其他两个线程。 4. 使用信号量Semaphore: 创建一个Semaphore对象和3个线程。在每个线程中使用Semaphore对象的acquire()方法获取许可,然后在循环打印对应的字符,最后调用Semaphore对象的release()方法释放许可,并通知其他两个线程获取许可。 以上这四种方式都可以实现多线程每个线程挨着打印abc的效果。然而,具体的选择取决于实际情况,例如需要考虑线程的数量、同步机制的复杂度、线程间协作的方式等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值