gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:14:07 25 4
gpt4 key购买 nike

我只想打印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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com