首页 > 解决方案 > 线程程序,输入一个输入并停止“hello world”输入并一直输入另一个输入,直到输入“quit”?

问题描述

这是一个将打印出“Hello world!”的程序。每三秒钟。你会得到一个输入框来写一条消息,但是我怎样才能停止消息“Hello world!” 当我输入一个新的输入?并且每次我写一条新消息之前的消息也会停止写吗?例如:控制台输出:Hello World!你好世界!你好世界!赢!(然后我输入 Win! 并停止 Hello world!) 赢!(每三秒赢一次,直到我输入另一个输入文本)。微笑!(新输入:微笑和“赢!”停止。

public class Main {

    public static void main(String[] args) throws InterruptedException {
        
        Thread t1 = new Thread(new myThread());
        Thread t2 = new Thread(new inputThread());
        
        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }
}

public class myThread implements Runnable {
    
    private boolean stop = false;

    public synchronized void stop() {
        this.stop = true;
    }

    private synchronized boolean continues() {
        return this.stop == false;
    }

    @Override
    public void run() {
        while(continues()) {
            System.out.println("Hello world!");

            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
               
            }
        }
    }
} 


public class inputThread implements Runnable {
    
    private boolean stop = false;

    public synchronized void stop() {
        this.stop = true;
    }

    private synchronized boolean continues() {
        return this.stop == false;
    }
      
    @Override
    public void run() {
        
        while(continues()) {
            String message = showInputDialog("Write your message, type quit to shut down!");
            
            if(message.equals("quit")) {
                break;
            }

            else {
                System.out.println(message);
                 try {
                     Thread.sleep(3000);
                 } catch (InterruptedException e) {
                    
                 }
            }
        }
    }
}

标签: java

解决方案


Thread API曾经有一个方法stop()来停止线程。此类方法不安全,已被弃用。解释了为什么以及应该使用什么。


推荐阅读