草庐IT

三个线程交替打印ABC100次问题思考

wayn111 2023-04-16 原文

如题:使用三个线程交替打印ABC,直至100次代码实战

方法一:

使用notify()、wait()方法

public class PrintAbc {

    /**
     * 唤醒线程的状态值 state: threadA = 0, threadB = 1, threadC =2,
     */
    int state = 0;

    /**
     * 循环技术,初始值0
     */
    int count = 0;

    public void print(PrintAbc printAbc) {
        Thread threadA = new Thread(() -> {
            extracted(printAbc, "A", 0, 1);
        });

        Thread threadB = new Thread(() -> {
            extracted(printAbc, "B", 1, 2);
        });

        Thread threadC = new Thread(() -> {
            extracted(printAbc, "C", 2, 0);
        });

        threadC.start();
        threadB.start();
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        threadA.start();
    }

    /**
     * 交替打印abc,直至100次
     *
     * @param printAbc  锁对象
     * @param a         打印的字母, 对应A、B、C
     * @param needState 当前线程对应的state状态值
     * @param nextState 唤醒下一个线程所需state状态值
     */
    private void extracted(PrintAbc printAbc, String a, int needState, int nextState) {
        while (true) {
            synchronized (printAbc) {
                if (count >= 100) {
                    break;
                }
                if (printAbc.count < 100 && printAbc.state == needState) {
                    System.out.println(a);
                    printAbc.state = nextState;
                    printAbc.count++;
                    printAbc.notifyAll();
                } else {
                    try {
                        printAbc.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        PrintAbc printAbc = new PrintAbc();
        printAbc.print(printAbc);
    }
}

上述代码使用notify(),wait(),进行线程间的条件唤醒,state的初始状态是0,对应线程A,所以第一次打印字母也一定是A

方法二

使用ReentrantLock的Condition条件

public class PrintAbcByCondition {

    /**
     * 循环计数初始值0
     */
    static int count = 0;

    public void print() {
        ReentrantLock reentrantLock = new ReentrantLock();
        Condition conditionA = reentrantLock.newCondition();
        Condition conditionB = reentrantLock.newCondition();
        Condition conditionC = reentrantLock.newCondition();
        Thread threadA = new Thread(() -> {
            while (true) {
                try {
                    reentrantLock.lock();
                    // threadA进来打印A然后唤醒threadB
                    if (count < 100) {
                        System.out.println("A");
                        count++;
                        conditionB.signal();
                    }
                    conditionA.await();

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    reentrantLock.unlock();
                }
            }
        });
        Thread threadB = new Thread(() -> {
            while (true) {
                try {
                    reentrantLock.lock();
                    // threadB进来就阻塞等待threadA使用完毕
                    conditionB.await();
                    if (count < 100) {
                        System.out.println("B");
                        count++;
                        conditionC.signal();
                    }

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    reentrantLock.unlock();
                }
            }
        });
        Thread threadC = new Thread(() -> {
            while (true) {
                try {
                    reentrantLock.lock();
                    // threadC进来就阻塞等待threadB使用完毕
                    conditionC.await();
                    if (count < 100) {
                        System.out.println("C");
                        count++;
                        conditionA.signal();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    reentrantLock.unlock();
                }
            }
        });

        threadC.start();
        threadB.start();
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        threadA.start();
    }

    public static void main(String[] args) {
        new PrintAbcByCondition().print();
    }
}

使用ReentrantLock的Condition条件,很容易能实现三个线程之间的交替打印,需要注意的一点就是线程A是需要第一个执行,可以看到代码里threadA在等待1秒后在执行,也能确保是第一个进行打印,原因如下:

线程B和线程C中任意一个线程拿到锁都需要等待条件成立,线程C依赖线程B,而线程B依赖线程A,所以他们会一直阻塞直至线程A执行

上述两个方法中,核心问题就是如何实现线程间的条件唤醒,如方法一,我们可以自定义state状态变量来与各个线程绑定,每个线程都有自己对应的state状态,当state变量当前值与线程自身期望的state值相同才唤醒当前线程。也可以使用jucReentrantLock的提供的Condition条件完成线程间的条件唤醒

至此,三个线程交替打印ABC100次的实现方法介绍完毕

有关三个线程交替打印ABC100次问题思考的更多相关文章

  1. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  2. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  3. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  4. ruby - Fast-stemmer 安装问题 - 2

    由于fast-stemmer的问题,我很难安装我想要的任何ruby​​gem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=

  5. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  6. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  7. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. ruby-on-rails - 简单的 Ruby on Rails 问题——如何将评论附加到用户和文章? - 2

    我意识到这可能是一个非常基本的问题,但我现在已经花了几天时间回过头来解决这个问题,但出于某种原因,Google就是没有帮助我。(我认为部分问题在于我是一个初学者,我不知道该问什么......)我也看过O'Reilly的RubyCookbook和RailsAPI,但我仍然停留在这个问题上.我找到了一些关于多态关系的信息,但它似乎不是我需要的(尽管如果我错了请告诉我)。我正在尝试调整MichaelHartl'stutorial创建一个包含用户、文章和评论的博客应用程序(不使用脚手架)。我希望评论既属于用户又属于文章。我的主要问题是:我不知道如何将当前文章的ID放入评论Controller。

  10. 【高数】用拉格朗日中值定理解决极限问题 - 2

    首先回顾一下拉格朗日定理的内容:函数f(x)是在闭区间[a,b]上连续、开区间(a,b)上可导的函数,那么至少存在一个,使得:通过这个表达式我们可以知道,f(x)是函数的主体,a和b可以看作是主体函数f(x)中所取的两个值。那么可以有,  也就意味着我们可以用来替换 这种替换可以用在求某些多项式差的极限中。方法: 外层函数f(x)是一致的,并且h(x)和g(x)是等价无穷小。此时,利用拉格朗日定理,将原式替换为 ,再进行求解,往往会省去复合函数求极限的很多麻烦。使用要注意:1.要先找到主体函数f(x),即外层函数必须相同。2.f(x)找到后,复合部分是等价无穷小。3.要满足作差的形式。如果是加

随机推荐