循环打印FooBar

力扣多线程测试题-循环打印FooBar

此博客为力扣多线程测试题,针对各答案进行解析补充知识点,可先自测:原测试题链接

需求:

两个不同的线程将会共用一个 FooBar 实例:
线程 A 将会调用 foo() 方法
线程 B 将会调用 bar() 方法
请设计修改程序,以确保 “foobar” 被输出 n 次。
例输入:n=1,例输出:foobar
例输入:n=5,例输出:foobarfoobarfoobarfoobarfoobar

待修改代码:

class FooBar {
  public void foo() {
    for (int i = 0; i < n; i++) {
      print("foo");
    }
  }

  public void bar() {
    for (int i = 0; i < n; i++) {
      print("bar");
    }
  }
}

一、使用sleep()方法

仅仅使用sleep()方法,判断标志值,即可进行多线程更替,此处展示main()方法,后续不展示

public class FooBar {

	private int n;
	private int fCount;
	private int bCount;

	public FooBar(int n) {
		this.n = n;
	}

	public void foo(Runnable printFoo) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			while (fCount != bCount) {
				Thread.sleep(1);
			}
			printFoo.run();
			fCount++;
		}
	}

	public void bar(Runnable printBar) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			while (fCount == bCount) {
				Thread.sleep(1);
			}
			printBar.run();
			bCount++;
		}
	}

	public static void main(String[] args) throws InterruptedException {

		FooBar fooBar = new FooBar(5);

		Thread fooThread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					fooBar.foo(new Runnable() {

						@Override
						public void run() {
							System.out.print("foo");
						}
					});
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});

		Thread barThread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					fooBar.bar(new Runnable() {

						@Override
						public void run() {
							System.out.print("bar" + "\n");
						}
					});
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});

		fooThread.start();
		barThread.start();
	}

}

二、volatile修饰符

	volatile boolean flag = true;

	public void foo(Runnable printFoo) throws InterruptedException {

		for (int i = 0; i < n;) {
			if (flag) {
				printFoo.run();
				flag = false;
				i++;
			}
		}
	}

	public void bar(Runnable printBar) throws InterruptedException {

		for (int i = 0; i < n;) {
			if (!flag) {
				printBar.run();
				flag = true;
				i++;
			}
		}
	}

volatile修饰符:修饰共享变量后,每个线程要操作变量时会从主内存中将变量拷贝到本地内存作为副本,当线程操作变量副本并写回主内存后,会通过 CPU 总线嗅探机制告知其他线程该变量副本已经失效,需要重新从主内存中读取。保证了不同线程对共享变量操作的可见性,也就是说一个线程修改了 volatile 修饰的变量,当修改后的变量写回主内存时,其他线程能立即看到最新值。

详细可参考:volatile修饰符

三、synchronized关键字

	volatile boolean flag = true;
	private final Object object = new Object();

	public void foo(Runnable printFoo) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			synchronized (object) {
				while(!flag) {
					object.wait();
				}
				printFoo.run();
				flag = false;
				object.notifyAll();
			}
		}

	}

	public void bar(Runnable printBar) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			synchronized (object) {
				while(flag) {
					object.wait();
				}
				printBar.run();
				flag = true;
				object.notifyAll();
			}
		}
	}

详细可参考:synchronized

四、可重入锁 + Condition类

	Lock lock = new ReentrantLock(true);
	private final Condition condition = lock.newCondition();
	volatile boolean flag = true;

	public void foo(Runnable printFoo) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			lock.lock();
			try {
				while (!flag) {
					condition.await();
				}
				printFoo.run();
				flag = false;
				condition.signal();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}

	}

	public void bar(Runnable printBar) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			lock.lock();
			try {
				while (flag) {
					condition.await();
				}
				printBar.run();
				flag = true;
				condition.signal();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				lock.unlock();
			}
		}
	}

Condition类:从整体上来看 Object 的 wait 和 notify/notifyAll 是与对象监视器 Synchronized 配合完成线程间的等待/通知机制,而Condition 的 await和 signal/signalAll 是与 Lock 配合完成等待通知机制。前者是java底层级别的,后者是语言级别的,两者用法基本类似,后者具有更高的可控制性和扩展性。
详细可参考:Condition类

五、CyclicBarrier 类

	volatile boolean flag = true;
	CyclicBarrier cyclicBarrier = new CyclicBarrier(2);

	public void foo(Runnable printFoo) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			while (!flag);
			printFoo.run();
			flag = false;
			try {
				cyclicBarrier.await();
			}catch(BrokenBarrierException e) {
				e.printStackTrace();
			}
		}
	}

	public void bar(Runnable printBar) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			try {
				cyclicBarrier.await();
			}catch(BrokenBarrierException e) {
				e.printStackTrace();
			}
			printBar.run();
			flag = true;
		}
	}

CyclicBarrier类:可以理解为构造方法创建n个线程,如果其中一个线程执行遇到await()则阻塞,等待其他线程执行也遇到await()阻塞;若当前线程为最后一个遇到await()阻塞的线程时,则唤醒全部线程执行并做下一次线程组任务。
详细可参考:CyclicBarrier

六、CountDownLatch 类

	volatile boolean flag = true;
	CountDownLatch countDownLatch = new CountDownLatch(2);

	public void foo(Runnable printFoo) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			while (!flag) {
				countDownLatch.countDown();
				countDownLatch.await();
			}
			printFoo.run();
			flag = false;
		}
	}

	public void bar(Runnable printBar) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			while (flag) {
				countDownLatch.countDown();
				countDownLatch.await();
			}
			printBar.run();
			flag = true;
		}
	}

CountDownLatch:是一个同步工具类,用来协调多个线程之间的同步,或者说起到线程之间的通信(而不是用作互斥的作用)。能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成一些任务,然后在CountDownLatch上等待的线程就可以恢复执行接下来的任务。
详细可参考:CountDownLatch 类

CyclicBarrierCountDownLatch对比:

  • CountDownLatch的计数器只能使用一次,而CyclicBarrier的计数器可以使用reset()方法重置,可以使用多次,所以CyclicBarrier能够处理更为复杂的场景;
  • CyclicBarrier还提供了一些其他有用的方法,比如getNumberWaiting()方法可以获得CyclicBarrier阻塞的线程数量,isBroken()方法用来了解阻塞的线程是否被中断;
  • CountDownLatch允许一个或多个线程等待一组事件的产生,而CyclicBarrier用于等待其他线程运行到栅栏位置。

七、Semaphore类

	private Semaphore foo = new Semaphore(1);
	private Semaphore bar = new Semaphore(0);

	public void foo(Runnable printFoo) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			foo.acquire();
			printFoo.run();
			bar.release();
		}
	}

	public void bar(Runnable printBar) throws InterruptedException {

		for (int i = 0; i < n; i++) {
			bar.acquire();
			printBar.run();
			foo.release();
		}
	}

Semaphore类:信号量控制,详情参考:Semaphore

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值