使用Java中的线程打印语句 [英] Printing a statement using threads in Java

查看:391
本文介绍了使用Java中的线程打印语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用线程在Java中打印一条语句,其中每个线程都应打印该语句的一部分.但是,以下代码并非总是以正确的顺序输出语句.

I am trying to print a statement in Java using threads, where each thread should print part of the statement. However, following code does not always output statement in correct order.

class NewThread implements Runnable {
    String msg;
    Thread t;
    NewThread(String str) {
        t = new Thread(this);
        msg = str;
    }
    public void run() {
        PrintMsg(msg);
    }
    synchronized void PrintMsg(String msg) {
        System.out.println(msg);
        try {
            wait();
        } catch (InterruptedException e) {
            System.out.println("Exception");
        }
        System.out.println(msg);
        notify();
    }
}
class ThreadDemo {
    public static void main(String args[]) {
        NewThread t1, t2, t3;
        t1 = new NewThread("Humphry Dumprey");
        t2 = new NewThread("went to the hill");
        t3 = new NewThread("to fetch a pail of water");
        t1.t.start();
        t2.t.start();
        t3.t.start();
        try {
            t1.t.join();
            t2.t.join();
            t3.t.join();
        } catch (InterruptedException e) {
            System.out.println("Main Thread Interrupted");
        }
    }
}

我怀疑线程间通信有问题.

推荐答案

我认为您的问题出在此方法中:

I think your problem is in this method:

synchronized void PrintMsg(String msg) {
    System.out.println(msg);
    try {
        wait();
    } catch (InterruptedException e) {
        System.out.println("Exception");
    }
    System.out.println(msg);
    notify();
}

调用它的线程将调用wait(),这将导致它们无限期地等待某人调用notify().但是没有notify()的其他任何调用,因此它们都将在此停止.

The thread that call it are going to call wait() which causes them to wait indefinitely for someone to call notify(). But there are no other calls to notify() so they all will stop there.

此外,因为方法是synchronized,所以每个线程也在等待自己的NewThread实例.我想您是要让所有线程都在等待并在同一个对象上进行通知吗?

Also, because the method is synchronized each thread is also waiting on it's own NewThread instance. I think you meant to have all threads waiting and notifying on the same object?

来自评论:

想要等待一个线程,直到它完成对语句的编写为止.它应该像这样:线程1打印"Humphry Dumprey"线程2打印去山上"线程3打印取一桶水",这三个线程应按顺序执行,以使语句按正确的顺序打印

want to wait a thread until it finishes writing a part of statement. It should be like this : Thread 1 prints "Humphry Dumprey" Thread 2 prints "went to the hill" Thread 3 prints "to fetch a pail of water" and these three threads should execute in sequence such that the statement gets printed in right sequence.

我从不理解这类问题.线程的全部要点是并行异步运行.如果希望他们连续打印3件东西,则应改用1个线程.

I never understand these sorts of questions. The whole point of threads are that the run asynchronously in parallel. If you want them to print 3 things in a row then 1 thread should be used instead.

如果您需要执行某些任务,那么有几种不同的方法可以实现.

If you need to do this for some assignment then there a couple different ways you can do it.

  • 每个线程可以在同一AtomicInteger上同步.如果整数为1,则线程#1将执行其打印;如果整数为2,则线程#2将进行打印....您可以按value字段的顺序将其传递给NewThread构造函数.打印后,它们会增加整数和notifyAll()的值.

  • Each thread could synchronize on the same AtomicInteger. Thread #1 would do its print if the integer was 1, thread #2 when it is 2, .... You could pass in the order as a value field to the NewThread constructor. After they print they values they increment the integer and notifyAll().

static final AtomicInteger counter = new AtomicInteger(1);
...
synchronized (counter) {
    // looping like this is always recommended
    while (counter.get() != value) {
       counter.wait();
    }
    System.out.println(...);
    counter.incrementAndGet();
    counter.notifyAll();
}

  • 您可以使用2个CountdownLatch,因此线程#2调用countDown1.await();,线程#3等待countDown2.await();.然后,在线程#1打印其消息后,它调用countDown1.countDown(),而在线程#2打印其消息后,它调用countDown2.countDown().

  • You could use 2 CountdownLatch so thread #2 calls countDown1.await(); and thread #3 waits for countDown2.await();. Then after thread #1 prints its message it calls countDown1.countDown() and after thread #2 prints its message it calls countDown2.countDown().

    这篇关于使用Java中的线程打印语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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