《2021/03/22》多线程编码

此代码示例展示了如何使用Java的同步机制(synchronized关键字,ReentrantLock和Condition)实现线程间的协调,以交叉打印字符序列。在第一个例子中,两个线程交替打印'A'和'B';第二个例子扩展到三个线程,以'A'、'B'和'C'的顺序交叉打印。这些示例演示了在多线程环境下如何有效地控制执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 交叉打印AB

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

public class ABDemo {

}

class ABPrint {
    private boolean flag = false;

    public synchronized void printA() {
        while (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("A");
        flag = true;
        this.notifyAll();
    }

    public synchronized void printB() {
        while (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("B");
        flag = false;
        this.notifyAll();
    }


    public static void main(String[] args) {
        ABPrint demo = new ABPrint();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                demo.printA();
            }
        }, "A").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                demo.printB();
            }
        }, "B").start();

    }
}


class BAPrint {
    private volatile boolean flag = false;

    private Object o = new Object();

    public void printA() {
        synchronized (o) {
            while (flag) {
                try {
                    o.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            flag = true;
            System.out.println("A");
            o.notify();
        }
    }

    public void printB() {
        synchronized (o) {
            while (!flag) {
                try {
                    o.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("B");
            flag = false;
            o.notify();
        }
    }

    public static void main(String[] args) {
        BAPrint demo = new BAPrint();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                demo.printA();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                demo.printB();
            }
        }, "B").start();

    }
}

class LockDemo{
    private ReentrantLock mylock = new ReentrantLock();
    private Condition condition = mylock.newCondition();

    private volatile boolean flag = false;

    public void printA() {
        try {
            mylock.lock();
            while (flag) {
                condition.await();
            }
            System.out.println("A");
            flag = true;
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            mylock.unlock();
        }
    }

    public void printB() {
        try {
            mylock.lock();
            while (!flag) {
                condition.await();
            }
            System.out.println("B");
            flag = false;
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            mylock.unlock();
        }
    }

    public static void main(String[] args) {
        LockDemo demo = new LockDemo();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                demo.printA();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                demo.printB();
            }
        }, "B").start();
    }

}

2. 交叉打印ABC

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

public class ABC_LockCondition {

    private static Lock lock = new ReentrantLock();

    private static Condition A = lock.newCondition();
    private static Condition B = lock.newCondition();
    private static Condition C = lock.newCondition();

    private static int count = 0;


    static class ThreadA extends Thread {
        @Override
        public void run() {
            try {
                lock.lock();
                for (int i = 0; i < 10; i++) {
                    while (count % 3 != 0)
                        A.await();  // 释放lock锁,ThreadC 会唤醒该线程继续执行
                    System.out.println("A");
                    count++;
                    B.signal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    static class ThreadB extends Thread {
        @Override
        public void run() {
            try {
                lock.lock();
                for (int i = 0; i < 10; i++) {
                    while (count % 3 != 1)
                        B.await();
                    System.out.println("B");
                    count++;
                    C.signal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    static class ThreadC extends Thread {
        @Override
        public void run() {
            try {
                lock.lock();
                for (int i = 0; i < 10; i++) {
                    while (count % 3 != 2) {
                        C.await();
                    }
                    System.out.println("C");
                    count++;
                    A.signal();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        new ThreadA().start();
        new ThreadB().start();
        new ThreadC().start();
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值