当前位置: 首页 > news >正文

两个线程交替打印数字

好久没写这个东西了,有点忘了,本来想百度一下偷个懒得的,但是网上发现尽是类似方案A,

但是我觉得方案A有点弊端,o.notify 是随机的,不能100%保证完全的顺序,所以我写了一下PlanB方便自己偷懒,也方便大家学习使用。

方案A:

package com.exam.spring.demo;

public class PrintA {

private static Object o = new Object();

static class A extends Thread {

@Override
public synchronized void run() {
synchronized (o) {
for (int i = 0; i < 100; i = i + 2) {
System.out.println("A" + i);
try {
o.wait();
o.notify();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}

}
}
}

static class B extends Thread {
@Override
public void run() {
synchronized (o) {
for (int i = 1; i < 100; i = i + 2) {
System.out.println("B" + i);

try {
o.notify();
o.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

}
}
}
}


public static void main(String[] args) {
Thread A = new A();
Thread B = new B();
// B.join();
A.start();
B.start();
}
}

方案B:

package com.exam.spring.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintB {

private static Lock lockA = new ReentrantLock();
private static Condition conditionA = lockA.newCondition();
private static Condition conditionB = lockA.newCondition();

static class A extends Thread {

@Override
public void run() {
lockA.lock();

try {
for (int i = 0; i < 10; i = i + 2) {
System.out.println("A" + i);
conditionB.signal();
conditionA.await();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lockA.unlock();
}
}
}

static class B extends Thread {
@Override
public void run() {
lockA.lock();
try {
for (int i = 1; i < 10; i = i + 2) {
System.out.println("B" + i);
conditionA.signal();
conditionB.await();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lockA.unlock();
}
}
}

public static void main(String[] args) throws InterruptedException {
Thread A = new A();
Thread B = new B();
// 保证一定先是A
A.join();
A.start();
B.start();
}
}


http://www.mrgr.cn/news/56405.html

相关文章:

  • nosql课本习题
  • hiveserver与beeline
  • Go 语言中格式化动词
  • 【人工智能】Transformers之Pipeline(二十):令牌分类(token-classification)
  • QT开发:详解Qt样式表(QSS):美化界面的应用
  • HCIP-HarmonyOS Application Developer 习题(十五)
  • 鸿蒙开发:两个重磅更新,鸿蒙版微信要来了!
  • Java学习Day50:唤醒八戒(Excel相关)
  • 中间件之Seata
  • Python酷库之旅-第三方库Pandas(160)
  • Linux基础命令(入门)
  • Java框架之MyBatis Plus
  • linux介绍与基本指令
  • Linux系统基础-进程间通信(2)_命名管道和System V通信
  • 【linux】线程 (三)
  • python虚拟环境安装
  • [LeetCode] 814. 二叉树剪枝
  • github加速 DevSidecar 1.8.8
  • 免费送源码:Java+ssm+MySQL SSM二手物品管理系统 计算机毕业设计原创定制
  • AutoSar AP CM实例说明符的使用方法总结
  • 开头的例子的理解
  • 【系统规划与管理师】历年各章节分值汇总(论文)
  • C++ 进阶:类相关特性的深入探讨
  • 伺服增量式和绝对式的本质区别?
  • 基因检测4 - 多囊肾
  • flask服务通过gunicorn启动,supervised管理服务