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

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 lock
        lock.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.kler.cn/news/341856.html

相关文章:

  • js短路求值
  • 网络安全社区和论坛
  • Java入门:10.Java中的包
  • 使用Java调用OpenAI API并解析响应:详细教程
  • 【含文档】基于Springboot+Android的校园论坛系统(含源码+数据库+lw)
  • LeetCode讲解篇之1043. 分隔数组以得到最大和
  • 服装生产管理的现代化:SpringBoot框架
  • 《C++职场中设计模式的学习与应用:开启高效编程之旅》
  • Leetcode.20 有效的括号
  • OpenStreetMap介绍
  • 研发中台拆分之路:深度剖析、心得总结与经验分享
  • Linux_进程概念详解
  • MySql外键约束
  • 舞韵流转:SpringBoot实现古典舞在线交流新体验
  • Pytest测试用例生命周期管理-Fixture
  • VBA即用型代码手册:将工作表复制到已关闭的工作簿
  • YOLO11改进|SPPF篇|引入YOLOv9提出的SPPELAN模块
  • uni-app之旅-day04-商品列表
  • 旅游管理智能化转型:SpringBoot系统设计与实现
  • 基于证书的身份验证方式及示例