多线程Hello World [英] Multi threaded Hello World

查看:162
本文介绍了多线程Hello World的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用两个线程,您应该打印"Hello World Hello World Hello World Hello World Hello World Hello World".

在两个线程中,一个应打印"Hello:",另一个应打印"World".

我可以使用不同的类来做到这一点,例如,您好,世界各一个 我也可以通过内部类做到这一点

有没有一种方法,使得只有一个主类而没有内部类?

解决方案

有没有一种方法,使得只有一个主类而没有内部类?

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

< rant>这让我感到计算机科学设计不佳.用线程编写的全部要点是它们独立并行运行.通常,当每个线程都从工作队列中拉出然后将结果放入结果队列之类时,就会发生协调.每当您有一个需要对此进行大量协调的线程程序时,您就极有可能不使用线程. </rant>

但是,由于每个人都对我以前的回答不满意,可能是因为它不能完美地解决他们的作业问题,因此,我将添加一些逻辑来协调两个线程之间的内容,并吐出"Hello World ...". /p>

这两个线程需要能够锁定某些东西,相互发出信号,并知道它们什么时候应该等待或打印.因此,我将添加一个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;
                    }
                }
            }
        }
    }
}

Using two threads you should print "Hello World Hello World Hello World Hello World Hello World Hello World ".

In two threads one should print "Hello: and another thread "World".

I can do this with different classes such as one each for hello and world I can also do it with an inner class

Is there a way such that there's only one main class and and no inner class?

解决方案

Is there a way such that there's only one main class and and no inner class?

Sure. You could pass in the string to print into your Main class. Of course the tricky part is to coordinate the threads so they actually print out "HelloWorld" instead of "WorldHello" or other permutations. The threads are going to run in parallel with no guarantee of order. That's the whole point of threaded programs -- they run asynchronously. Trying to force a particular word output negates the purpose of using threads.

<rant> This smacks to me of a poorly designed computer science assignment. The whole point of writing with threads is that they run independently in parallel. Coordination typically happens when each thread is pulling from a work queue and then putting results into a results queue or something. Anytime you have a threaded program that needs to coordinate this much, you should most likely not be using threads. </rant>

But, since everyone is down-voting my previous answer probably because it doesn't solve their homework problem perfectly, I'll add some logic to coordinate between the two threads and spit out "Hello World...".

The two threads need to be able to lock on something, signal each other, and know when they should be waiting or printing. So I'll add a boolean printHello and will lock on a common lock object that is passed in:

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;
                    }
                }
            }
        }
    }
}

这篇关于多线程Hello World的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆