线程同步-同步三个线程以打印012012012012 .....无法正常工作 [英] Thread Synchronization - Synchronizing three threads to print 012012012012..... not working

查看:83
本文介绍了线程同步-同步三个线程以打印012012012012 .....无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试同步三个线程以打印012012012012....但是它不能正常工作.每个线程都分配有一个编号,当它从主线程接收到信号时将打印该编号.以下程序有问题,我无法捕获.

I am trying to synchronize three threads to print 012012012012.... but it is not working correctly. Each thread is assigned a number which it prints when it receives a signal from main thread. There is something wrong with the following program which I am not able to catch.

public class Application {
    public static void main(String[] args) {

        int totalThreads = 3;
        Thread[] threads = new Thread[totalThreads];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new MyThread(i);
            threads[i].start();
        }

        int threadIndex = 0;
        while (true) {
            synchronized(threads[threadIndex]) {
                threads[threadIndex].notify();
            }

            threadIndex++;
            if (threadIndex == totalThreads) {
                threadIndex = 0;
            }
        }
    }
}

class MyThread extends Thread {
    private int i;

    public MyThread(int i) {
        this.i = i;
    }

    @Override
    public void run() {
        while (true) {
            synchronized(this) {
                waitForSignal();
                System.out.println(i);
            }
        }
    }

    private void waitForSignal() {
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

推荐答案

您需要更多的协调. notify调用不会立即唤醒线程并强制其继续执行.而是将notify视为向该线程发送电子邮件以使其可以继续进行.想象一下,如果您想让3个朋友按顺序给您打电话.您向朋友1发送了一封电子邮件给您打电话,等待了一秒钟,然后向朋友2发送了一封电子邮件,等待了一秒钟,然后向朋友3发送了一封电子邮件.您认为会按确切的顺序打电话给您吗?

You need more coordination. the notify call does not immediately wake up the thread and force it to proceed. Instead, think of notify as sending an email to the thread to let it know that it can proceed. Imagine if you wanted your 3 friends to call you in order. You sent friend 1 an email to call you, waited one second, sent an email to friend 2, waited a second, and sent an email to friend 3. do you think you'd get called in that exact order?

增加协调的一种方法是拥有一些共享状态,该状态指示轮到谁了.如果您所有的朋友都能看到您的房子,您可以在房子外面放一个数字,指示该轮到谁了.每个朋友都会等到看到他们的号码,然后再打电话.

one way to add more coordination would be to have some shared state which indicates whose turn it is. if all your friends could see your house, you could put a number on the outside of the house indicating whose turn it was to call. each friend would wait until they saw their number, and then call.

这篇关于线程同步-同步三个线程以打印012012012012 .....无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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