Java程序之多线程顺序打印 ABC--Synchronized(推荐)

题目:
按顺序打印 ABC ABC ABC ...。有这么一个多线程场景问题:有三个线程,线程1执行(输出A)完成之后线程2执行(输出B),线程2执行完之后线程3执行(输出C),线程3执行完成之后线程1执行...,整体循环50次,写程序实现。

 

算法思路:
要求按照顺序打印,即A、B、C轮流打印,每个字母打印一次后换下一个字母继续打印,循环进行。

1. 创建一个名为ThreadThreadp的类,其中包含一个flag变量,用于标记当前应该打印哪个字母。初始值为0,表示先打印A。
2. 在ThreadThreadp类中定义三个同步方法printa()、printb()和printc(),分别用于打印A、B、C字母。这三个方法都需要传入一个ThreadThreadp对象作为参数。
3. 在printa()方法中,首先判断flag是否为0,如果是,则打印A字母,并将flag设置为1,然后唤醒其他等待的线程。接着调用wait()方法让当前线程进入等待状态。
4. 在printb()方法中,首先判断flag是否为1,如果是,则打印B字母,并将flag设置为2,然后唤醒其他等待的线程。接着调用wait()方法让当前线程进入等待状态。
5. 在printc()方法中,首先判断flag是否为2,如果是,则打印C字母,并让当前线程休眠1秒,然后将flag设置为0,最后唤醒其他等待的线程。接着调用wait()方法让当前线程进入等待状态。
6. 在main方法中,创建ThreadThreadp对象t,以及三个PrintA、PrintB、PrintC对象,分别传入t作为参数。然后创建三个线程t1、t2、t3,分别执行这三个PrintA、PrintB、PrintC对象的run()方法。最后启动这三个线程。
7. 运行程序,可以看到按照顺序打印出ABC三个字母。

原始版本

package abc;

public class PrintABCMain {
    public static void main(String[] args) {
        Info info = new Info();
        Thread threadA = new Thread(new MyThreadA(info));
        Thread threadB = new Thread(new MyThreadB(info));
        Thread threadC = new Thread(new MyThreadC(info));
        threadA.start();
        threadB.start();
        threadC.start();
    }
}

class MyThreadA implements Runnable {
    private Info info;

    public MyThreadA(Info info) {
        this.info = info;
    }

    @Override
    public void run() {
        try {
            info.printA();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

class MyThreadB implements Runnable {
    private Info info;

    public MyThreadB(Info info) {
        this.info = info;
    }


    @Override
    public void run() {
        try {
            info.printB();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

class MyThreadC implements Runnable {
    private Info info;

    public MyThreadC(Info info) {
        this.info = info;
    }

    @Override
    public void run() {
        try {
            info.printC();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

class Info {
    private volatile int flag = 0;
    private int num;

    public synchronized void printA() throws InterruptedException {
        while (true) {
            if (num >= 5) {
                break;
            }
            if (flag == 0) {
                System.out.print("A");
                flag = 1;
                notifyAll();
            }
            wait();
        }
    }

    public synchronized void printB() throws InterruptedException {
        while (true) {
            if (num >= 5) {
                break;
            }
            if (flag == 1) {
                System.out.print("B");
                flag = 2;
                notifyAll();
            }
            wait();
        }
    }

    public synchronized void printC() throws InterruptedException {
        while (true) {
            if (num >= 5) {
                break;
            }
            if (flag == 2) {
                System.out.println("C");
                flag = 0;
                notifyAll();
                num++;
            }
            wait();
        }
    }


}
View Code

改进版本

package abc2;

import java.util.concurrent.atomic.AtomicInteger;

public class PrintABCMain {
    public static void main(String[] args) {
        AtomicInteger synObj = new AtomicInteger(0);
        Thread threadA = new Thread(new MyThread(synObj, "A", 0));
        Thread threadB = new Thread(new MyThread(synObj, "B", 1));
        Thread threadC = new Thread(new MyThread(synObj, "C", 2));
        threadA.start();
        threadB.start();
        threadC.start();
    }

}

class MyThread extends Thread {
    private AtomicInteger synObj;
    private String name;
    private int flag;
    private int count;


    public MyThread(AtomicInteger synObj, String name, int flag) {
        this.synObj = synObj;
        this.name = name;
        this.flag = flag;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (synObj) {
                if (synObj.get() % 3 == flag) {

                    synObj.set(synObj.get() + 1);
                    System.out.println(name);
                    count++;
                    synObj.notifyAll();

                    if (count == 5) {
                        break;
                    }

                } else {
                    try {
                        synObj.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}
View Code

 

 

原文链接:https://blog.csdn.net/m0_74344909/article/details/139902351

posted @ 2024-12-12 10:10  chenxiangxiang  阅读(12)  评论(0编辑  收藏  举报