美文网首页
[leetcode]1114. 按序打印

[leetcode]1114. 按序打印

作者: nzdxwl | 来源:发表于2019-12-17 00:50 被阅读0次

问题描述

我们提供了一个类:

public class Foo {
public void one() { print("one"); }
public void two() { print("two"); }
public void three() { print("three"); }
}
三个不同的线程将会共用一个 Foo 实例。

线程 A 将会调用 one() 方法
线程 B 将会调用 two() 方法
线程 C 将会调用 three() 方法
请设计修改程序,以确保 two() 方法在 one() 方法之后被执行,three() 方法在 two() 方法之后被执行。

示例 1:

输入: [1,2,3]
输出: "onetwothree"
解释:
有三个线程会被异步启动。
输入 [1,2,3] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 two() 方法,线程 C 将会调用 three() 方法。
正确的输出是 "onetwothree"。
示例 2:

输入: [1,3,2]
输出: "onetwothree"
解释:
输入 [1,3,2] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 three() 方法,线程 C 将会调用 two() 方法。
正确的输出是 "onetwothree"。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/print-in-order
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

给出的Foo类如下:

class Foo {

    public Foo() {
        
    }

    public void first(Runnable printFirst) throws InterruptedException {
        
        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
    }

    public void second(Runnable printSecond) throws InterruptedException {
        
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
    }

    public void third(Runnable printThird) throws InterruptedException {
        
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    }
}

简单问题的简单解法:

一开始还有点蒙,方法说是one、two、three;然后线程A调用one,线程B调用two、线程C调用three。
接着线程可以随意调方法了,one、two、three也变成first, second, third了,还好题目较简单,看看注释说明大致就清楚了。解起来也简单,下面是一个简单的解法, 执行结果通过如下:

执行用时 : 10 ms, 在所有 java 提交中击败了97.10%的用户
内存消耗 : 36.2 MB , 在所有 java 提交中击败了100.00%的用户

class Foo {
    volatile int state = 0;
    
    public Foo() {
        
    }

    public void first(Runnable printFirst) throws InterruptedException {
        while(state!=1){
            if(state == 0){
                // printFirst.run() outputs "first". Do not change or remove this line.
                printFirst.run();
                state++;
            }
        }

    }

    public void second(Runnable printSecond) throws InterruptedException {
        while(state != 2){
            if(state == 1){
                // printSecond.run() outputs "second". Do not change or remove this line.
                printSecond.run();
                state++;
            }
        }

    }

    public void third(Runnable printThird) throws InterruptedException {
        while(state != 3){
            if(state == 2){
                // printThird.run() outputs "third". Do not change or remove this line.
                printThird.run();
                state++;
            }
        }
    }
}

第一个方法可以不用判断,直接打印和自增就可以,不过差别不大。

相关文章

网友评论

      本文标题:[leetcode]1114. 按序打印

      本文链接:https://www.haomeiwen.com/subject/mwmjnctx.html