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

Java经典面试题-多线程打印

thread+synchronized

就好像一个圆圈,A->B->C->A。。。。。

synchronized能够保证多个线程进入实,只用一个线程能进入。

/**多线程交替打印* */
public class Task {private final Object lock = new Object();private int count = 0;public static void main(String[] args) {Task task = new Task();new Thread(()->{for(int i=0;i<10;i++){task.printA();}}).start();new Thread(()->{for(int i=0;i<10;i++){task.printB();}}).start();new Thread(()->{for(int i=0;i<10;i++){task.printC();}}).start();}public void printA(){synchronized (lock){while(count!=0){try {lock.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.print("A");count++;lock.notifyAll();}}public void printB(){synchronized (lock){while(count!=1){try{lock.wait();}catch (InterruptedException e){e.printStackTrace();}}System.out.print("B");count++;lock.notifyAll();}}public void printC(){synchronized (lock){while(count!=2){try {lock.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.print("C");count=0;lock.notifyAll();}}
}

ReentrantLock

public class Task2 {private  final Lock lock=new ReentrantLock();private final Condition condition=lock.newCondition();private final Condition condition1=lock.newCondition();private final Condition condition2=lock.newCondition();private int state=0;public static void main(String[] args) {Task2 tash2 = new Task2();Thread thread = new Thread(tash2::printA);Thread thread1 = new Thread(tash2::printB);thread.start();thread1.start();}private void printA(){// get locklock.lock();try{for(int i=0;i<10;i++){while(state!=0){condition.await();}System.out.print("a");state=1;condition1.signal();}} catch (InterruptedException e) {throw new RuntimeException(e);}finally {lock.unlock();}}private  void printB(){lock.lock();try{for(int i=0;i<10;i++){while(state!=1){condition1.await();}System.out.print("b");state=0;condition.signal();}} catch (InterruptedException e) {throw new RuntimeException(e);}finally {lock.unlock();}}
}

Semaphore

信号量机制,设置刚开始的值为1,如果减去1的结果>=0,则执行该线程,否则不执行,执行完释放,值加1

public final void acquireShared(int arg) {if (tryAcquireShared(arg) < 0)acquire(null, arg, true, false, false, 0L);}/*** Acquires in shared mode, aborting if interrupted.  Implemented* by first checking interrupt status, then invoking at least once* {@link #tryAcquireShared}, returning on success.  Otherwise the* thread is queued, possibly repeatedly blocking and unblocking,* invoking {@link #tryAcquireShared} until success or the thread* is interrupted.* @param arg the acquire argument.* This value is conveyed to {@link #tryAcquireShared} but is* otherwise uninterpreted and can represent anything* you like.* @throws InterruptedException if the current thread is interrupted*/public final void acquireSharedInterruptibly(int arg)throws InterruptedException {if (Thread.interrupted() ||(tryAcquireShared(arg) < 0 &&acquire(null, arg, true, true, false, 0L) < 0))throw new InterruptedException();}
package com.r.ThreadTask;import javax.swing.text.Segment;
import java.util.concurrent.Semaphore;public class Task3 {private final Semaphore semaphore=new Semaphore(1);private final Semaphore semaphore1=new Semaphore(0);private final Semaphore semaphore2=new Semaphore(0);public static void main(String[] args) {Task3 task3 = new Task3();Thread thread = new Thread(task3::printA);Thread thread1 = new Thread(task3::printB);Thread thread2 = new Thread(task3::printC);thread.start();thread1.start();thread2.start();}private void printA(){for(int i=0;i<10;i++){try {semaphore.acquire();} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.print("a");semaphore1.release();}}private void printB(){for(int i=0;i<10;i++){try {semaphore1.acquire();} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.print("b");semaphore2.release();}}private void printC(){for(int i=0;i<10;i++){try {semaphore2.acquire();} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.print("c");semaphore.release();}}
}

http://www.lryc.cn/news/457335.html

相关文章:

  • FireFox简单设置设置
  • Sollong手机——一站式Web3生态解决方案
  • 《重生到现代之从零开始的数据结构生活》—— 顺序表1
  • 2本书让你轻松入门大模型!《大模型入门:技术原理与实战应用》+《自然语言处理:大模型理论与实践》
  • 【JDK17 | 1】Java 17 深入剖析:新特性与变革
  • strtok
  • 零信任身份安全的基本原则
  • 【AAOS】Android Automotive 9模拟器源码下载及编译
  • 手动降级wsl中的numpy
  • 极客兔兔Gee-Cache Day7
  • R包:APAlyzer从RNA-seq数据计算APA表达丰度
  • YOLOv11改进策略【损失函数篇】| 利用MPDIoU,加强边界框回归的准确性
  • dayu_widgets-简介
  • 改变数组页面重新渲染的操作/那些操作不会重新渲染页面以及解决方法
  • 米哈游Android面试题汇总及参考答案
  • 搜维尔科技:【应用】Xsens动作捕捉技术为奇幻电影注入活力
  • useradd命令:添加Linux新用户
  • Python+ffmpeg实现字幕视频合并
  • 垂直分库分表、水平分库分表
  • rocksdb merge的简单记录
  • 安卓开发板_MTK联发科评估套件_安卓开发板Demo板
  • maven指定模块快速打包idea插件Quick Maven Package
  • i春秋云境靶场之CVE-2022-26965
  • 流域生态系统服务评价、水文水生态分析、碳收支、气候变化影响、制图等领域中的应用
  • 超像素提取加svm训练,鼠标点击选择标签(左键为正样本,右键为负样本)
  • Vue 中引入 ECharts 的详细步骤与示例
  • 在 EC2 AWS 中开启防火墙后将自己锁定在 SSH 之外
  • OpenGL 进阶系列02 - OpenGL绘制三角形的必要步骤
  • MySql基础34题写题记录(11-20)
  • 设计模式——单例模式(1)