java - 具有两个线程的控制台应用程序

标签 java concurrency java.util.scanner

我只想打印learning...只要输入1

  package a;

    import java.util.Scanner;

    class main extends Thread {
        static String n;

        Scanner reader = new Scanner(System.in);
        public void run() {
            n = reader.nextLine();
        }

        public static void main(String args[]) throws InterruptedException {
            (new Thread(new main())).start();
            n="5";
            System.out.println("1 = ON\n0 = OFF");
            while (n.equals("1")) {
                System.out.println("Learning..");
            }
        }
    }

最佳答案

您可能有兴趣阅读生产者-消费者模式。你可以看这里http://javarevisited.blogspot.fr/2012/02/producer-consumer-design-pattern-with.html并尝试类似的东西

class main extends Thread {

// a thread-safe queue for decoupling reading and writing threads avoiding
// synchronization issues. The capacity of the queue is 1 to avoid reading (producing) a
// command without having handled (consumed) the previous before
private static final BlockingQueue<String> sharedQueue = new LinkedBlockingQueue<>(1);

Scanner reader = new Scanner(System.in);

public void run() {
    while (true) {
        String s = reader.nextLine();
        try {
            //if the queue is empty, adds the element, 
            //otherwise blocks waiting for the current element to be handled by main thread
            sharedQueue.put(s);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }
}

public static void main(String args[]) throws InterruptedException {
    (new Thread(new main())).start();

    System.out.println("1 = ON\n0 = OFF");
    while (true) {
        //will block till an element is available, then removes and handles it
        final String s = sharedQueue.take();
        if ("1".equals(s)) {
            System.out.println("Learning..");
        }
    }
}

}

关于java - 具有两个线程的控制台应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38712557/

相关文章:

overriding - 覆盖 jre_lib 类

java - GIJ(Java 的 GNU 解释器)是否足够稳定以用于商业用途?

java - 在不同位置关闭 FileOutputStream 的最佳编码实践

c++ - 在线程之间共享数据时如何从不变性中获益?

java - 我收到此消息 : Error: b cannot be resolved to a variable

java - 如何在 String 中获取 jsch shell 命令输出

go - 在没有互斥体的情况下同时读取或写入时会发生什么

c# - 为什么 ConcurrentBag<T> 不实现 ICollection<T>?

java - Java Scanner 究竟是如何解析 double 的?

java - 使用套接字时替代扫描仪