同时创建多个线程,它们都访问一个对象中的同步方法,怎么确保第一个线程最先拿到对象锁,否则,怎么保证多个线程之间的有序通信

好像在上述情况下,无法保证第一个线程最想拿到对象锁。。。

package bao;

class TickTock {
    String state;

    synchronized void tick(boolean running) {
        if(!running) {
            state = "ticked";
            notify();
            
        }

        System.out.print("Tick ");

        state = "ticked";

        notify();
        try {
                wait();
        }
        catch(InterruptedException exc) {
            System.out.println("Thread interrupted.");
        }
    }

    synchronized void tock(boolean running) {
        if(!running) {
            state = "tocked";
            notify();
            return;
        }

        System.out.println("Tock");

        state = "tocked";

        notify();
        try {
                wait();
        }
        catch(InterruptedException exc) {
            System.out.println("Thread interrupted.");
        }
        
    }
}

class MyThread implements Runnable {
    Thread thrd;
    TickTock ttOb;

    MyThread(String name, TickTock tt) {
        thrd = new Thread(this, name);
        ttOb = tt;
        thrd.start();
    }

    public void run() {
        if(thrd.getName().compareTo("Tick") == 0) {
            for(int i = 0; i<5; i++ ) ttOb.tick(true);
            ttOb.tock(false);
        }
        else {
            for(int i = 0; i<5; i++ ) ttOb.tock(true);
                ttOb.tock(false);
        }
    }
}

class D {
    public static void main(String[] args) {
        TickTock tt = new TickTock();
        MyThread mt1 = new MyThread("Tick", tt);
        MyThread mt2 = new MyThread("Tock", tt);

        try {
            mt1.thrd.join();
            mt2.thrd.join();        
        } catch(InterruptedException exc) {
            System.out.println("Main thread interrpted.");
        }
    }
}

结果如下图,并不能保证第一个是Tick。。。。多次运行会发现也有第一个是Tock的。。。。

同时创建多个线程,它们都访问一个对象中的同步方法,怎么确保第一个线程最先拿到对象锁,否则,怎么保证多个线程之间的有序通信