首页 > 试题广场 >

建立三个线程A、B、C,A线程打印10次字母A,B线程打印1

[问答题]
建立三个线程A、B、C,A线程打印10次字母A,B线程打印10次字母B,C线程打印10次字母C,但是要求三个线程同时运行,并且实现交替打印,即按照ABCABCABC的顺序打印。
使用Java实现
/**
 * 顺序打印-进阶版
 *
 * 有三个线程,分别只能打印A,B和C
 * 要求按顺序打印ABC,打印10次
 * 输出示例:
 * ABC
 * ABC
 * ABC
 * ......
 *
 * 解法:使用循环数组配合线程通信
 */
public class Demo {
    // 要输出的信息数组
    private static String[] INFO = {"A","B","C"};
    // 数组下标
    private static volatile int INDEX = 0;
    // 打印次数
    private static final int NUM = 10;

    // 线程所包含的任务
    static class Task implements Runnable{
        private String info; //需要打印的字符串信息

        public Task(String info) {
            this.info = info;
        }

        @Override
        public void run() {
            //循环打印
            for (int i = 0; i < NUM; i++) {
                //获取同步锁
                synchronized (Task.class){
                    //检查是否轮到当前线程
                    while(!info.equals(INFO[INDEX])){ //每次唤醒都需要判断是否满足条件
                        try {
                            //不满足条件则主动等待并释放锁
                            Task.class.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    //输出字符串信息
                    System.out.print(info);
                    //若输出信息是最后一个时则换行
                    if(INDEX == INFO.length - 1){
                        System.out.println();
                    }
                    //轮到下一个线程打印
                    INDEX = (INDEX + 1) % INFO.length;
                    Task.class.notifyAll();
                }
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new Task("A")).start();
        new Thread(new Task("B")).start();
        new Thread(new Task("C")).start();
    }
}


发表于 2023-02-19 11:42:10 回复(0)
package concurrent;

import java.util.concurrent.locks.LockSupport;

public class LockSupportDemo2 {

    static Thread A,B,C;

    public static void main(String[] args) {
        A = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                LockSupport.park();
                System.out.print("A");
                LockSupport.unpark(B);
            }
        });
        B = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                LockSupport.park();
                System.out.print("B");
                LockSupport.unpark(C);
            }
        });
        C = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                LockSupport.unpark(A);
                LockSupport.park();
                System.out.print("C");
            }
        });
        A.start();
        B.start();
        C.start();
    }
}

发表于 2021-02-23 15:56:50 回复(2)
自旋锁解法,不加同步块和JDK锁(线程启动部分没贴出来)
class Task3{
    private volatile boolean firstDone;
    private volatile boolean secondDone;
    private volatile boolean thirdDone = true;
    volatile int sum =0;
    void first(){
        while (true){
            while (!thirdDone){
                //等待第三个线程的完成
            }
            sum++;
            System.out.println(Thread.currentThread().getName()+" :  A  计数:"+sum);
            thirdDone=false;
            firstDone=true;
            if(sum==28)return;
        }
    }
    void second(){
        while (true){
            while (!firstDone){
                //等待一个线程完成
            }
            sum++;
            System.out.println(Thread.currentThread().getName()+" :  B  计数:"+sum);
            secondDone=true;
            firstDone=false;
            if(sum==29)return;
        }
    }
    void third(){
        while (true){
            while (!secondDone){
                //等待第二线程完成
            }
            sum++;
            System.out.println(Thread.currentThread().getName()+" :  C  计数:"+sum);
            System.out.println("===================================================");
            secondDone=false;
            thirdDone=true;
            if(sum==30)return;
        }
    }
}


编辑于 2021-02-24 14:01:45 回复(0)
public void test() { for (int x = 1; x <= 10; x++) { CompletableFuture.runAsync(() -> { System.out.println("线程A" );
        }).thenRunAsync(() -> { System.out.println("线程B");
        }).thenRunAsync(() -> { System.out.println("线程C");
        }); try { TimeUnit.SECONDS.sleep(1);
      }catch (Exception e) { e.printStackTrace();
      }
    }
}
发表于 2021-02-18 17:35:47 回复(0)
package real;

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

public class DiffPrint {
    private volatile int num = 0;
    private Lock lock = new ReentrantLock();
    private Condition a = lock.newCondition(),
             b = lock.newCondition(),
             c = lock.newCondition();
    public void printA() {
        while (num < 30) {
            lock.lock();
            while (num > 0 && num % 3 != 0) {
                try {
                    a.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("a");
            num++;
            b.signal();
            lock.unlock();
        }
    }
    public void printB() {
        while (num < 30) {
            lock.lock();
            while (num % 3 != 1) {
                try {
                    b.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("b");
            num++;
            c.signal();
            lock.unlock();
        }
    }

    public void printC() {
        while (num < 30) {
            lock.lock();
            while (num % 3 != 2) {
                try {
                    c.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("c");
            num++;
            a.signal();
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        DiffPrint dp = new DiffPrint();
        new Thread(() -> {
            dp.printA();
        }).start();
        new Thread(() -> {
            dp.printB();
        }).start();
        new Thread(() -> {
            dp.printC();
        }).start();
    }
}

发表于 2022-03-09 13:14:19 回复(0)
package com.lyr.common.demo.aqs;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author lyr
 * @create 2021/1/27 22:27
 */
public class SimpleLock {
    public static void main(String[] args) throws Exception {
        new Thread(()->{
            synchronized (lock) {
                while (modCount<30) {

                    if (A=='A') {
                        modCount++;
                        System.out.println(A);
                        A++;
                    }else{
                        lock.notifyAll();
                        try {
                            // if (modCount>=30) break;
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                lock.notifyAll();
            }
        }).start();
        new Thread(()->{
            synchronized (lock) {
                while (modCount<30) {
                    if (A=='B'){
                        modCount++;
                        System.out.println( A);
                        A++;
                    }else{
                        try {
                            lock.notifyAll();
                            // if (modCount>=30) break;
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                lock.notifyAll();
            }
        }).start();
        new Thread(()->{
            synchronized (lock) {
                while (modCount<30) {
                    if (A=='C') {
                        modCount++;
                        System.out.println( A );
                        A = 'A';
                    }else{
                        lock.notifyAll();
                        // if (modCount>=30) break;
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                lock.notifyAll();

            }
        }).start();
    }
    volatile static char A = 'A';
    volatile  static Object lock = new Object();
    volatile static int modCount = 0;
}

发表于 2021-01-28 17:10:05 回复(0)
    @Data
    static
    class Test implements Runnable {

        private static Integer totalNum = 0;

        private static String[] order;

        private Integer printTimes;

        private String name;

        public Test(String name, Integer printTimes) {
            this.name = name;
            this.printTimes = printTimes;
        }

        @Override
        public void run() {
            int startNum = 1;
            while (startNum <= printTimes) {
                if (currentName(totalNum).equals(name)) {
                    System.out.print(name);
                    startNum++;
                    totalNum++;
                    try {
                        Thread.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                }
            }
        }

        public String currentName(Integer totalNum) {
            return order[totalNum % order.length];
        }
    }

    public static void main(String[] args) {
        Test.order = new String[]{"A", "B", "C"};
        new Thread(new Test("A", 10)).start();
        new Thread(new Test("B", 10)).start();
        new Thread(new Test("C", 10)).start();
    }


发表于 2021-01-28 11:36:41 回复(0)