Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

java - How to "synchronize" threads to run one after another in order?

I want to make my method to print out 4 lines of "Hello world!", but my code seems to not work as I want. Is there a way that I have a guarantee that it will run as I want? Sometimes I get 2 lines, sometimes the words are in wrong order, and so on. Sometimes it prints words how I want, but mostly not. Sorry for any mistakes in my code that can hurt your eyes, I'm still learning and im here because of it. Thanks for any advice.

public class PrintHelloWorld {

final Lock lock = new ReentrantLock(true);
private volatile String state = "inactive";

public void printHelloWorld() {
    LocksManager manager = new LocksManager();

    Thread t1 = new Thread(() -> {
        synchronized (manager.getObject(0)) {
            for (int i = 0; i < 4; i++) {
                System.out.print("Hello ");
                try {
                    manager.notify(1);
                    state = "running t2";
                    while(!state.equals("running t1"))
                        manager.wait(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    Thread t2 = new Thread(() -> {
        synchronized (manager.getObject(1)) {
            for (int i = 0; i < 4; i++) {
                System.out.print("world");
                try {
                    manager.notify(2);
                    state = "running t3";
                    while (!state.equals("running t2"))
                        manager.wait(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    Thread t3 = new Thread(() -> {
        synchronized (manager.getObject(2)) {
            for (int i = 0; i < 4; i++) {
                System.out.println("!");
                try {
                    manager.notify(0);
                    state = "running t1";
                    while (!state.equals("running t3"))
                        manager.wait(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    {
        t1.start();
        t2.start();
        t3.start();
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

private class LocksManager {
    private volatile Object[] locks;

    public LocksManager() {
        locks = new Object[3];

        for (int i=0; i<3; i++)
            locks[i] = new Object();
    }

    public Object getObject(int number) {
        return locks[number];
    }

    public void wait(int number) throws InterruptedException {
        synchronized (locks[number]) {
            locks[number].wait();
        }
    }

    public void notify(int number) {
        synchronized (locks[number]) {
            locks[number].notify();
        }
    }

}
}

The output shoud look like this:

Hello world!
Hello world!
Hello world!
Hello world!

But sometimes it looks like this:

Hello world!
Hello !
worldHello !
worldHello !
world

Or this:

Hello !
world
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Threads are supposed to be Asynchronous, which is the behavior you see in your executions.

If you need to force them to be synchronous, please take a look at Future's in https://www.baeldung.com/java-executor-service-tutorial. You can make a List and iterate the list using an executor and the .get method to wait for a result of each thread.

I'm not sure about you use case, but threads is a very challenging subject.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...