带有多线程Java的Hello World [英] Hello World with Multithreading Java

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

问题描述

我想了解如何使用关键字:wait,notify/All,synchronized,因此我决定尝试一个简单的示例.基本上,我想做的是创建两个将打印字符串的线程.第一个线程的字符串为"Hello",第二个线程的字符串为"World".

I'm tying to understand how to use the keywords: wait, notify/All, synchronized, so I decided to try with a simple example. Basically what I'm trying to do is to create two threads that are going to print a string. The first thread has the string "Hello", while the second thread has the String "World".

我想要的输出如下: 你好 世界 你好 世界 你好 世界 ...

The output I'd like to reach is the following: Hello World Hello World Hello World ...

这是我到目前为止编写的代码,但是现在的输出是: 你好 你好 你好 ... 世界 世界 世界 ...

This is the code I wrote so far, but the output right now is: Hello Hello Hello ... World World World ...

错误在哪里?谢谢你. :)

Where is/are the mistake/s? Thank you. :)

代码如下:

class MyThread implements Runnable {
    private SimpleSyncThread sync;
    private String s;

    public MyThread(SimpleSyncThread sync, String s) {
        this.sync = sync;
        this.s = s;
    }

    public static void pause(long time) {
        try {Thread.sleep(time); }
        catch (InterruptedException e) {Thread.currentThread().interrupt();}
    }

    @Override
    public void run() {
        synchronized (sync) {
            for (int i = 0; i < 10; i++) {
                sync.print(s);
            }
        }
    }
}

public class SimpleSyncThread {

    public void print(String s) {
        System.out.println(s);
        MyThread.pause(200);
    }

    public static void main(String[] args) {
        SimpleSyncThread sync = new SimpleSyncThread();
        MyThread st1 = new MyThread(sync, "Hello");
        MyThread st2 = new MyThread(sync, "World");

        Thread t1 = new Thread(st1);
        Thread t2 = new Thread(st2);

        t1.start();
        t2.start();
    }
}

推荐答案

您在这里持有锁,因此一次只能打印一个进程

You are holding the lock here so only one process can print at a time

   synchronized (sync) {
        for (int i = 0; i < 10; i++) {
            sync.print(s);
        }
    }

您可以使用以下方法暂时解除锁定:

Instead of doing this you can release the lock temporarily with

   synchronized (sync) {
        for (int i = 0; i < 10; i++) {
            sync.print(s);
            // I have done my bit, wake other threads.
            sync.notifyAll();
            try {
                // give up the lock and let another thread run.
                sync.wait(10);
            } catch(InterruptedException ie) {
                throw new AssertionError(ie);
            }
        }
    }


您可能想到的是我所说的乒乓球测试.您不会在真正的程序中执行此操作,但是这种模式会产生有用的微基准.


What you might have had in mind is what I call a Ping Pong test. You wouldn't do this in a real program but this pattern makes a useful micro-benchmark.

public class PingPongMain {
    public static void main(String[] args) throws InterruptedException {
        boolean[] next = {false};
        AtomicInteger count = new AtomicInteger();
        Thread t1 = new Thread(() -> {
            try {
                synchronized (next) {
                    for(;;) {
                        // handle spurious wake ups.
                        while (next[0])
                            next.wait();

                        System.out.println("ping");

                        // state change before notify
                        next[0] = true;
                        next.notifyAll();
                    }
                }
            } catch (InterruptedException e) {
                // expected
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                synchronized (next) {
                    for(;;) {
                        // handle spurious wake ups.
                        while (!next[0])
                            next.wait();

                        System.out.println("pong");

                        // state change before notify
                        next[0] = false;
                        next.notifyAll();

                        count.incrementAndGet();
                    }
                }
            } catch (InterruptedException e) {
                // expected
            }
        });

        t1.start();
        t2.start();

        Thread.sleep(5000);
        t1.interrupt();
        t2.interrupt();
        System.out.println("Ping ponged " + count + " times in 5 seconds");

    }
}

打印

ping
pong
ping
pong
.. deleted ...
Ping ponged 323596 times in 5 seconds

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

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