三个线程轮流执行顺序打印ABC,依次是ABCABCABC......(三种方式)

news/2024/5/17 15:48:25 标签: 多线程, semaphore, Synchronized, Lock

1.使用synchronized悲观锁

(秋招阿里的一个笔试题,应该写的比较复杂,然后就没有然后了o(╥﹏╥)o)

public class ThreadThreadp {
    private int flag = 0;
    public synchronized void printa() throws InterruptedException {
       while (true)
       {
           if(flag ==0)
           {
               System.out.print("A");
               flag = 1;
               notifyAll();
           }
           wait();
       }
    }
    public synchronized   void printb() throws InterruptedException {
        while (true)
        {
            if(flag ==1)
            {
                System.out.print("B");
                flag = 2;
                notifyAll();
            }
            wait();
        }
    }
    public synchronized void printc() throws InterruptedException {
        while (true) {
            if (flag == 2) {
                System.out.print("C");
                Thread.sleep(1000);
                flag = 0;
                notifyAll();
            }
            wait();
        }
    }
    public static void main(String[]args) throws InterruptedException
    {
        ThreadThreadp t = new ThreadThreadp();
        PrintA printA = new PrintA(t);
        PrintB printB = new PrintB(t);
        PrintC printC = new PrintC(t);
        Thread t1 = new Thread(printA);
        Thread t2 = new Thread(printB);
        Thread t3 = new Thread(printC);
        t1.start();
        t2.start();
        t3.start();
        //Thread t11 = new Thread(printA);
        //Thread t21 = new Thread(printB);
        //Thread t31 = new Thread(printC);
        //t11.start();
        //t21.start();
        //t31.start();

    }

}

class PrintA implements Runnable{
    private  ThreadThreadp t;
    PrintA(ThreadThreadp t){
        this.t=t;
    }
    @Override
    public void run() {
        try {
            t.printa();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class PrintB implements Runnable{

    private  ThreadThreadp t;
    PrintB(ThreadThreadp t){
        this.t=t;
    }
    @Override
    public void run() {
        try {
            t.printb();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class PrintC implements Runnable{
    private  ThreadThreadp t;
    PrintC(ThreadThreadp t){
        this.t=t;
    }
    @Override
    public void run() {
        try {
            t.printc();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2.使用Lock+Condition

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

public class threadsan {
    public static void main(String [] args)
    {
        PrintABC printABC = new PrintABC();
        new Thread(new Runnable() {
            @Override
            public void run() {
                printABC.printA();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                printABC.printB();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                printABC.printC();
            }
        }).start();
    }
}

class PrintABC{
    private final Lock lock = new ReentrantLock();
    private Condition lockA = lock.newCondition();
    private Condition lockB = lock.newCondition();
    private Condition lockC = lock.newCondition();
    int flag = 0;

    public void printA()
    {
        lock.lock();
        try {
            while (true)
            {
                while (flag!=0)
                    lockA.await();
                System.out.print("A");
                flag =1;
                lockB.signal();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printB()
    {
        lock.lock();
        try {
            while (true)
            {
                while (flag!=1)
                    lockB.await();
                System.out.print("B");
                flag =2;
                lockC.signal();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void printC()
    {
        lock.lock();
        try {
            while (true)
            {
                while (flag!=2)
                    lockC.await();
                System.out.print("C");
                Thread.sleep(1000);
                flag =0;
                lockA.signal();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

semaphore实现">3.使用Semaphore实现

//semaphore没用过。。。参考

import java.util.concurrent.Semaphore;

/**
 * Created by huali on 2018/7/25.
 */
public class PrintABCRotationUsingSemaphore {
    public static void main(String[] args) {
        PrintABCUsingSemaphore printABC = new PrintABCUsingSemaphore();
        new Thread(() -> printABC.printA()).start();
        new Thread(() -> printABC.printB()).start();
        new Thread(() -> printABC.printC()).start();
    }
}

class PrintABCUsingSemaphore {
    private Semaphore semaphoreA = new Semaphore(1);
    private Semaphore semaphoreB = new Semaphore(0);
    private Semaphore semaphoreC = new Semaphore(0);
    //private int attempts = 0;


    public void printA() {
        print("A", semaphoreA, semaphoreB);
    }

    public void printB() {
        print("B", semaphoreB, semaphoreC);
    }

    public void printC() {
        print("C", semaphoreC, semaphoreA);
    }

    private void print(String name, Semaphore currentSemaphore, Semaphore nextSemaphore) {
        for (int i = 0; i < 10; ) {
            try {
                currentSemaphore.acquire();
                //System.out.println(Thread.currentThread().getName()+" try to print "+name+", attempts : "+(++attempts));
                System.out.println(Thread.currentThread().getName() +" print "+ name);
                i++;
                nextSemaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

另外参考链接 三个线程轮流执行顺序打印ABC(一):使用Semaphore实现
使用信号量Semaphore循环打印ABC
三个线程轮流执行顺序打印ABC(二):使用Lock+Condition实现
三个线程轮流执行顺序打印ABC(三):使用Lock实现


http://www.niftyadmin.cn/n/1280043.html

相关文章

面试题:Tomcat的架构是什么,http请求从浏览器到进入tomcat服务器的全过程?

1.Tomcat Tomcat是java的应用web服务器&#xff0c;使用java编写的需要运行在JVM之上。Tomcat实现了javaEE的规范&#xff0c;包括java servlet&#xff0c;java servlet pages&#xff0c;java webservlet等&#xff0c;Tomcat默认提供的。Tomcat最重要的是实现了servlet规范…

京东一面:图中两个顶点的最短路径——Dijkstra算法原理

数据结构好像忘了看关于图的&#xff0c;然后只说了&#xff0c;深度优先遍历和广度优先遍历。 原文地址: http://www.cnblogs.com/skywang12345/p/3711516.html Dijkstra算法 1.定义概览 Dijkstra(迪杰斯特拉)算法是典型的单源最短路径算法&#xff0c;用于计算一个节点到其他…

java8中的stream

public class ArraysSort {public static void main(String[] args){//大写转换String [] wordlist {"Pdsgdfgdf","jfsdkjfksdfg","sdfusdf"};List<String> output Arrays.stream(wordlist).map(String::toUpperCase).collect(Collector…

bootstrap表格某一列值相同时_pandas读取表格后的常用数据处理操作

作者丨Sp4rkW来源丨凹凸数据大家好&#xff0c;我是Sp4rkW今天给大家讲讲pandas读取表格后的一些常用数据处理操作。这篇文章其实来源于自己的数据挖掘课程作业&#xff0c;通过完成老师布置的作业&#xff0c;感觉对于使用python中的pandas模块读取表格数据进行操作有了更深层…

JAVA NIO 缓冲区buffer实例

缓冲区&#xff08;Buffer&#xff09;Java NIO中的Buffer用于和NIO通道进行交互。如你所知&#xff0c;数据是从通道读入缓冲区&#xff0c;从缓冲区写入到通道中的。 缓冲区本质上是一块可以写入数据&#xff0c;然后可以从中读取数据的内存。这块内存被包装成NIO Buffer对象…

PHP-ThinkPHP将后台模板与框架做结合

九、将后台模板与框架做结合 模板整合思路&#xff1a; ①确定页面的访问路径&#xff08;模块、控制器、方法&#xff09; ②新建对应的控制器方法&#xff0c;在方法中调用模板 ③将模板页面移动到对应的视图目录下&#xff08;创建子目录&#xff09; ④将静态资源文件…

选项在哪_趣味测试:你喜欢哪一双公主鞋,测你上辈子积了什么德

阅读本文前&#xff0c;请您先点击上面的“ 蓝色字体”&#xff0c;再点击“关注”&#xff0c;这样您就可以继续免费收到文章了。每天都有分享&#xff0c;完全是免费订阅&#xff0c;请放心关注。图文来源于&#xff0c;如有侵权&#xff0c;请联系删除。趣味测试&#xff1a…