Java two threads running alternately -- Take alternating printing odd and even numbers as an example

Keywords: Java

The purpose of this article is to run two threads alternately. Look at the code directly without more beeps

public class Work2 {
    static final Object object = new Object();

    public static void main(String[] args) {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (object) {
                    for (int i = 1; i < 10; i += 2) {
                        System.out.println(Thread.currentThread().getName() + "    " + i);
                        object.notify();
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "t1");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (object) {
                    for (int i = 2; i < 10; i += 2) {
                        System.out.println(Thread.currentThread().getName() + "     " + i);
                        object.notify();
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }, "t2");
        t1.start();
        t2.start();
    }
}

The principle of this implementation is also very simple. Define an object. Because an object has and only has one lock, let two threads loop to unlock and lock the object, so as to achieve the purpose of running threads alternately;

I don't think this method is good enough. I'll continue to add it later. I hope the big guys can give me more advice!

Posted by Billett on Fri, 03 Jan 2020 13:02:55 -0800