Java三线程按序打印10次ABC (Lock实现与synchronized,wait,notify实现)

三线程循环打印ABC

方法一:使用Lock

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

public class Test {

    static private int cnt = 0;
    static Lock lk = new ReentrantLock();
    public static void main(String[] args) throws InterruptedException {
        Thread A = new Thread(new Runnable() {
            @Override
            public void run() {
                while(cnt <= 30) {
                    lk.lock();
                    if (cnt % 3 == 0) {
                        System.out.print("A ");
                        cnt++;
                    }
                    lk.unlock();
                }
            }
        });

        Thread B = new Thread(new Runnable() {
            @Override
            public void run() {
                while(cnt <= 30) {
                    lk.lock();
                    if (cnt % 3 == 1) {
                        System.out.print("B ");
                        cnt++;
                    }
                    lk.unlock();
                }
            }
        });

        Thread C = new Thread(new Runnable() {
            @Override
            public void run() {
                while(cnt <= 30) {
                    lk.lock();
                    if (cnt % 3 == 2) {
                        System.out.print("C\n");
                        cnt++;
                    }
                    lk.unlock();
                }
            }
        });
        A.start();
        B.start();
        C.start();
    }
}

方法二:synchronized,wait,noify实现
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test {

    public static void main(String[] args) throws InterruptedException {
        Object A = new Object();
        Object B = new Object();
        Object C = new Object();
        Thread At = new Thread(new Print(A, B), "A");
        Thread Bt = new Thread(new Print(B, C), "B");
        Thread Ct = new Thread(new Print(C, A), "C");
        At.sleep(100);
        At.start();
        Bt.sleep(100);
        Bt.start();
        Ct.sleep(100);
        Ct.start();
    }
}

class Print implements Runnable {

    Object nxt, cur;
    public Print(Object cur, Object nxt) {
        this.cur = cur;
        this.nxt = nxt;
    }
    @Override
    public void run() {
        for(int i = 0; i < 10; i++) {
            synchronized (cur) {
                synchronized (nxt) {
                    System.out.print(Thread.currentThread().getName());
                    nxt.notify();
                }
                try {
                    cur.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


你可能感兴趣的:(多线程,Java学习笔记)