经典线程面试题-两个线程交替打印

看到群里发了个面试题,实现两个线程交替打印从1到100,很基础,但是也很考验多线程的基本功,

自己开始能想到的是 synchronized 和 wait notifyAll 和Lock ,其他的都是参考网上的博客自己调试整理的

不多说,直接上代码

 通用字段,注意volatile的使用,保证可见性

public static int i = 1;
public volatile static int j = 1;
public volatile static boolean flag = false;
public static int count = 0;

public static Lock lock = new ReentrantLock();
public static Condition conditionA = lock.newCondition();
public static Condition conditionB = lock.newCondition();

private static CountDownLatch latch = new CountDownLatch(2);
private static AtomicInteger numA = new AtomicInteger();
private static AtomicInteger numB = new AtomicInteger();

private static byte[] block = new byte[0];

(1)使用 synchronized 和 wait notifyAll 来实现


public static void test6() {
		new Thread(() -> {
			while (i < 10) {
				synchronized (block) {
					if (flag) {
						try {
							block.wait();
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else {
						System.out.println(Thread.currentThread().getName()
								+ "----" + (i++));
						flag = true;
						block.notifyAll();
					}

				}
			}
		}).start();

		new Thread(() -> {
			while (j < 10) {
				synchronized (block) {

					if (!flag) {
						try {
							block.wait();
						} catch (Exception e) {
							e.printStackTrace();
						}
					} else {
						System.out.println(Thread.currentThread().getName()
								+ "----" + (j++));
						flag = false;
						block.notifyAll();
					}

				}
			}
		}).start();
	}

(2)使用Lock 实现

	public static void test2() {
		new Thread(() -> {
			while (i < 10) {

				try {
					lock.lock();
					while (!flag) {
						System.out.println(Thread.currentThread().getName()
								+ "----" + (i++));
						flag = true;
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		}).start();

		new Thread(() -> {
			while (j < 10) {

				try {
					lock.lock();
					while (flag) {
						System.out.println(Thread.currentThread().getName()
								+ "----" + (j++));
						flag = false;
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		}).start();
	}

(3)使用Lock 和 Condition 类实现,更加灵活一点

	public static void test4() {

		new Thread(() -> {
			try {
				lock.lock();
				while (i < 10) {
				if (flag) {
					conditionA.await();
				}
				flag = true;
				System.out.println(Thread.currentThread().getName() + "----"
						+ (i++));
				conditionB.signal();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}	).start();

		new Thread(() -> {

			try {
				lock.lock();
				while (j < 10) {
				if (!flag) {
					conditionB.await();
				}
				flag = false;
				System.out.println(Thread.currentThread().getName() + "----"
						+ (j++));
				conditionA.signal();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}	).start();
	}

(4)利用 AtomicInteger 和 volatile

public static void test5() {

		new Thread(() -> {
			while (numA.get() < 10) {
				if (!flag) {
					System.out.println(Thread.currentThread().getName()
							+ "----" + (numA.incrementAndGet()));
					flag = true;
				}
		    //   latch.countDown();

			}
		}).start();

		new Thread(() -> {
			while (numB.get() < 10) {
				if (flag) {
					System.out.println(Thread.currentThread().getName()
							+ "----" + (numB.incrementAndGet()));
					flag = false;
				}
			//	latch.countDown();

			}
		}).start();

	}

(5)使用信号去判断

public static void test1() {
		new Thread(() -> {
			while (i < 10) {
				if (!flag) {
					System.out.println(Thread.currentThread().getName()
							+ "----" + (i++));
					flag = true;
				}
			}
		}).start();

		new Thread(() -> {
			while (j < 10) {
				if (flag) {
					System.out.println(Thread.currentThread().getName()
							+ "----" + (-j++));
					flag = false;
				}
			}
		}).start();
	}

能想到方法,就是以上这几种,代码都是可用运行出正确结果的,欢迎补充指正

  • 1
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值