多线程按序交替打印

一、线程按序交替打印

效果展示:

A     1
A     2
A     3
A     4
A     5
B     1
B     2
B     3
B     4
B     5
C     1
C     2
C     3
C     4
C     5

代码实现:

package juc;

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

public class AlternativePrint {
    private ReentrantLock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();

    private int number = 1;

    public void loopA(){
        lock.lock();
        try {
            if (number != 1){
                conditionA.await();
            }

            for (int i = 1; i <= 5; i++){
                System.out.println(Thread.currentThread().getName() + "     " + i);
            }

            number = 2;
            conditionB.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void loopB(){
        lock.lock();
        try {
            if (number != 2){
                conditionB.await();
            }

            for (int i = 1; i <= 5; i++){
                System.out.println(Thread.currentThread().getName() + "     " + i);
            }

            number = 3;
            conditionC.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void loopC(){
        lock.lock();
        try {
            if (number != 3){
                conditionC.await();
            }

            for (int i = 1; i <= 5; i++){
                System.out.println(Thread.currentThread().getName() + "     " + i);
            }

            number = 1;
            conditionA.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("--------------------------------------------------");
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        final AlternativePrint alternativePrint = new AlternativePrint();

        new Thread("A"){
            @Override
            public void run() {
                for (int i= 0; i < 20; i++)
                    alternativePrint.loopA();
            }
        }.start();

        new Thread("B"){
            @Override
            public void run() {
                for (int i= 0; i < 20; i++)
                    alternativePrint.loopB();
            }
        }.start();

        new Thread("C"){
            @Override
            public void run() {
                for (int i= 0; i < 20; i++)
                    alternativePrint.loopC();
            }
        }.start();
    }
}

二、多线程交替打印10次abc实例

效果展示:

A     1
B     1
C     1
-----------------------------------------------------------------
A     1
B     1
C     1
-----------------------------------------------------------------

代码实现:

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

public class AlternativePrint {
    private ReentrantLock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();

    private int number = 1;

    public void loopA(){
        lock.lock();
        try {
            if (number != 1){
                conditionA.await();
            }

            for (int i = 1; i <= 1; i++){
                System.out.println(Thread.currentThread().getName() + "     " + i);
            }

            number = 2;
            conditionB.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void loopB(){
        lock.lock();
        try {
            if (number != 2){
                conditionB.await();
            }

            for (int i = 1; i <= 1; i++){
                System.out.println(Thread.currentThread().getName() + "     " + i);
            }

            number = 3;
            conditionC.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void loopC(){
        lock.lock();
        try {
            if (number != 3){
                conditionC.await();
            }

            for (int i = 1; i <= 1; i++){
                System.out.println(Thread.currentThread().getName() + "     " + i);
            }

            number = 1;
            conditionA.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("-----------------------------------------------");
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        final AlternativePrint alternativePrint = new AlternativePrint();

        new Thread("A"){
            @Override
            public void run() {
                for (int i= 0; i < 20; i++)
                    alternativePrint.loopA();
            }
        }.start();

        new Thread("B"){
            @Override
            public void run() {
                for (int i= 0; i < 20; i++)
                    alternativePrint.loopB();
            }
        }.start();

        new Thread("C"){
            @Override
            public void run() {
                for (int i= 0; i < 20; i++)
                    alternativePrint.loopC();
            }
        }.start();

    }
}

原文地址:https://www.cnblogs.com/ch-forever/p/10293741.html

时间: 2024-11-12 21:06:51

多线程按序交替打印的相关文章

Java多线程编程4--Lock的实例--实现生产者/消费者模式:一对一、多对多交替打印

1.实现生产者/消费者模式:一对一交替打印 public class MyService { private ReentrantLock lock= new ReentrantLock(); private Condition condition = lock.newCondition(); private boolean hasValue = false; public void set() { try{ lock.lock(); while (hasValue == true) { cond

多线程面试题之【三线程按顺序交替打印ABC的方法】

建立三个线程,线程名字分别为:A.B.C,要求三个线程分别打印自己的线程名字,但是要求三个线程同时运行,并且实现交替打印,即按照ABCABCABC的顺序打印.打印10轮,打印完毕控制台输出字符串:"打印完毕" 方法之一:使用Condition等待唤醒机制,代码如下: import java.util.concurrent.CountDownLatch; import java.util.concurrent.locks.Condition; import java.util.concu

java多线程 更优雅的实现线程同步:交替打印A、B LockSupport实现

一 问题概述 线程或者进程之间有两种关系 同步和互斥,我们通常实现同步方法是使用线程的等待唤醒机制,而等待唤醒机制的使用是建立在互斥的继承上的.但是同步线程并不一定是必须要实现互斥的.比如一个线程打印A,一个线程打印B.这两个线程就没有互斥关系,但是提出这么个需求:交替打印A.B .我们一般的解决方案,往往要使用wait()/notify机制. 二 LockSupport 介绍 LockSupport作为一个工具类,主要学习它的方法. park():在线程内调用,表示当前线程自我阻塞,直到获得许

(三)juc高级特性——虚假唤醒 / Condition / 按序交替 / ReadWriteLock / 线程八锁

8. 生产者消费者案例-虚假唤醒 参考下面生产者消费者案例: /* * 生产者和消费者案例 */ public class TestProductorAndConsumer { public static void main(String[] args) { Clerk clerk = new Clerk(); Productor pro = new Productor(clerk); Consumer cus = new Consumer(clerk); new Thread(pro, "生产

实现两个线程从0-100交替打印

分享一道多线程面试题,只是拿来练手的,这里通过两种方式去实现0-100交替打印,大家无聊的话,可以瞅两眼. 一.Synchronized实现: public class PrintNumberIncrInSynchronized { private static int number; private static final Object object = new Object(); public static void main(String[] args) { new Thread(()

字符串交替打印 操作方法

1 package cn.itcast.servlet; 2 3 import java.util.concurrent.LinkedBlockingQueue; 4 import java.util.concurrent.locks.Condition; 5 import java.util.concurrent.locks.Lock; 6 import java.util.concurrent.locks.ReentrantLock; 7 8 9 interface StringTurn 1

两个线程交替打印信息

看见一个关于两个线程交替打印信息的题目,题目大概是 子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次,试写出代码. 写了两个版本,一个是用了mutex,不用条件变量:另外一个是用条件变量. 第一个,不用条件变量 1 #include <stdio.h> 2 #include <string.h> 3 #include <pthread.h> 4 5 6 7 const int LOOP_

两个线程交替打印1-99

参考https://github.com/crossoverJie/JCSprout/blob/master/src/main/java/com/crossoverjie/actual/TwoThread.java从线程方面实现交替打印. public class Test { volatile boolean isEven = false; @org.junit.Test public void testfda() throws InterruptedException { Thread a

多线程-线程一打印1,2,3,4,5线程二打印6,7,8,9,10,线程三打印11,12,13,14,15,...直到45结束

多线程-线程一打印1,2,3,4,5线程二打印6,7,8,9,10,线程三打印11,12,13,14,15,...知道45结束 public class Exam3{ public static void main(String[]args){ MyThread t1=new MyThread("线程一"); MyThread t2=new MyThread("线程二"); MyThread t3=new MyThread("线程三"); t1.