读书人

面试题-三个线程循环打印ABC10次的几种

发布时间: 2013-10-12 11:54:04 作者: rapoo

面试题--三个线程循环打印ABC10次的几种解决方法
最近发现公司有份笔试试卷中有道多线程的题目有三个线程分别打印A、B、C,请用多线程编程实现,在屏幕上循环打印10次ABCABC…

这个最早好像是迅雷的面试题目吧,看到了然后就想重温一下这个题目的解决方法。

在本文中,给出了五种这个题目的解决方法:

使用sleep使用synchronized, wait和notifyAll使用Lock 和 Condition使用Semaphore使用AtomicInteger

下面依次给出每种解决方案的代码:

使用sleep

package my.thread.test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.atomic.AtomicInteger;public class AtomicIntegerExample {private AtomicInteger sycValue = new AtomicInteger(0);private static final int MAX_SYC_VALUE = 3 * 10;public static void main(String[] args) {AtomicIntegerExample example = new AtomicIntegerExample();ExecutorService service = Executors.newFixedThreadPool(3);service.execute(example.new RunnableA());service.execute(example.new RunnableB());service.execute(example.new RunnableC());service.shutdown();}private class RunnableA implements Runnable {public void run() {while (sycValue.get() < MAX_SYC_VALUE) {if (sycValue.get() % 3 == 0) {System.out.println(String.format("第%d遍",sycValue.get() / 3 + 1));System.out.println("A");sycValue.getAndIncrement();}}}}private class RunnableB implements Runnable {public void run() {while (sycValue.get() < MAX_SYC_VALUE) {if (sycValue.get() % 3 == 1) {System.out.println("B");sycValue.getAndIncrement();}}}}private class RunnableC implements Runnable {public void run() {while (sycValue.get() < MAX_SYC_VALUE) {if (sycValue.get() % 3 == 2) {System.out.println("C");System.out.println();sycValue.getAndIncrement();}}}}}


转载请注明出处http://mouselearnjava.iteye.com/blog/1949228 1 楼 leecyz 2013-09-29 这个题 面试时碰到几次

读书人网 >编程

热点推荐