Java-两个线程交替打印

notify() 和 wait()

public class TestAB {

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (this) {
                        notify();

                        System.out.println(Thread.currentThread().getName());
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

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

        Thread threadA = new Thread(runnable, "thread-a");
        Thread threadB = new Thread(runnable, "thread-b");
        threadA.start();
        threadB.start();
    }

}

 lock

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestAB {

    public static void main(String[] args) {
        Lock lock = new ReentrantLock(true);

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        lock.lock();
                        System.out.println(Thread.currentThread().getName());
                        try {
                            TimeUnit.MILLISECONDS.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } finally {
                        lock.unlock();
                    }
                }
            }
        };
        Thread threadA = new Thread(runnable, "thread-a");
        Thread threadB = new Thread(runnable, "thread-b");
        threadA.start();
        threadB.start();
    }
}

 总结

 第一种方式:两个线程互相唤醒。

 第二种方式:使用公平锁,每个线程一下。

你可能感兴趣的:(Java)