#Java Multithreading syncronization

5 messages · Page 1 of 1 (latest)

uncut junco
#

Hey everyone!. I need to get output like in screenshot pinned to this message.

How i can get it from this code? Code:

class MyThreads {
    public final static Object den = new Object();
    public final static Object ada = new Object();
    private static volatile boolean isLocked = true;

    public static int n;
    public static int m;

    public static Thread t1 = new Thread() {
        public void run() {
            synchronized (den) {
                for (int i = 0; i < 5; i++, n++)
                    System.out.println("Thread1 n = " + n);
                Thread.yield();
                synchronized (ada) {
                    ada.notifyAll();
                    try {
                        ada.wait();
                        ada.notifyAll();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    for (int i = 0; i < 5; i++, m++)
                        System.out.println("Thread1 m = " + m);
                    System.out.println("Thread1 success!");
                }
            }
        }
    };
    public static Thread t2 = new Thread() {
        public void run() {
            synchronized (ada) {
                try {
                    ada.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (int i = 0; i < 5; i++, m++)
                    System.out.println("Thread2 m = " + m);
                Thread.yield();
                synchronized (den) {
                    try {
                        den.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    for (int i = 0; i < 5; i++, n++)
                        System.out.println("Thread2 n = " + n);
                    System.out.println("Thread2 success!");
                }

            }
        }
    };
}

willow windBOT
#

This post has been reserved for your question.

Hey @uncut junco! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

uncut junco
#

You can test code with this:

public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> MyThreads.t1.run());
        Thread thread2 = new Thread(() -> MyThreads.t2.run());

        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();
    }

Code working like that:

uncut junco
#

But need to fix this like on previous screenshot.