多线程Hello World

Jai*_*ore 5 java multithreading

使用两个线程,您应该打印“Hello World Hello World Hello World Hello World Hello World Hello World”。

在两个线程中,一个应该打印“Hello:”,另一个线程应该打印“World”。

我可以使用不同的类来完成此操作,例如 hello 和 world 各一个,我也可以使用内部类来完成此操作

有没有一种方法可以让只有一个主类而没有内部类?

Gra*_*ray 5

有没有一种方法可以让只有一个主类而没有内部类?

当然。您可以传入要打印到主类中的字符串。当然,棘手的部分是协调线程,以便它们实际上打印出"HelloWorld"而不是"WorldHello"其他排列。线程将并行运行,不保证顺序。这就是线程程序的全部要点——它们异步运行。试图强制输出特定的单词就否定了使用线程的目的。

<rant> 这对我来说是一个设计糟糕的计算机科学作业。使用线程编写的全部要点是它们独立并行运行。当每个线程从工作队列中提取然后将结果放入结果队列或其他东西时,通常会发生协调。每当您有一个需要协调这么多的线程程序时,您很可能不应该使用线程。</咆哮>

但是,由于每个人都对我之前的答案投了反对票,可能是因为它不能完美解决他们的作业问题,所以我将添加一些逻辑来协调两个线程并吐出“Hello World...”。

这两个线程需要能够锁定某些内容、相互发出信号并知道何时应该等待或打印。因此,我将添加一个boolean printHello并将锁定传入的公共锁定对象:

public class HelloWorld implements Runnable {

    private static boolean printHello = true;

    private final String toPrint;
    private final boolean iPrintHello;
    private final Object lock;

    public static void main(String[] args) {
        final Object lock = new Object();
        // first thread prints Hello
        new Thread(new HelloWorld("Hello ", true, lock)).start();
        // second one prints World
        new Thread(new HelloWorld("World ", false, lock)).start();
    }

    public HelloWorld(String toPrint, boolean iPrintHello, Object lock) {
        this.toPrint = toPrint;
        this.iPrintHello = iPrintHello;
        this.lock = lock;
    }

    @Override
    public void run() {
        // don't let it run forever
        for (int i = 0; i < 1000 && !Thread.currentThread().isInterrupted(); ) {
            // they need to synchronize on a common, constant object
            synchronized (lock) {
                // am I printing or waiting?
                if (printHello == iPrintHello) {
                    System.out.print(toPrint);
                    // switch the print-hello to the other value
                    printHello = !printHello;
                    // notify the other class that it can run now
                    lock.notify();
                    i++;
                } else {
                    try {
                        // wait until we get notified that we can print
                        lock.wait();
                    } catch (InterruptedException e) {
                        // if thread is interrupted, _immediately_ re-interrupt it
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)