多线程交替打印的四种方法

多线程交替打印的四种方法

方法一: Wait/Notify

public class Print {
    boolean currentA = false;
    public synchronized void printA() {
        if (!currentA) {
            try {
                System.out.println("wait here");
                this.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        currentA = false;
        System.out.println("current Thread A:" + Thread.currentThread());
        this.notify();
    }

    public synchronized void printB() {
        if (currentA) {
            try {
                System.out.println("wait b here");
                this.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        currentA = true;
        System.out.println("current Thread B:" + Thread.currentThread());
        this.notify();
    }

    public static void main(String[] args) {
        Print p = new Print();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    p.printA();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    p.printB();
                }
            }
        }).start();
    }

}

​ 这里利用的是synchronized持有对象锁的特点,对于同样一个实例对象,同时只有一个线程可以进入对象内部执行方法,这样变相实现互斥的功能。但是利用的是重量级锁,也就是同步锁,虽然有锁升级的过程,但是性能还是比较低。下面用volatile 进行优化

方法二:自旋+volatile

**
 * @program: test
 * @description:
 * @author: Mr.Wang
 * @create: 2022-01-11 15:24
 **/
public class Print {
    volatile int num  = 0;
    public void printA() {
        while (num % 2 ==0) {
//            Thread.yield();
        }
        num++;
        System.out.println("current Thread A:" + Thread.currentThread()+num);
    }

    public void printB() {
        if (num%2 !=0) {
            try {
//                Thread.yield();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        num++;
        System.out.println("current Thread B:" + Thread.currentThread()+num);
    }

    public static void main(String[] args) {
        Print p = new Print();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    p.printA();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 50; i++) {
                    p.printB();
                }
            }
        }).start();
    }
}

利用了volitile的内存可见性的特点,但是使用了自旋,比较消耗CPU资源

方法三:lock

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

/**
 * @program: test
 * @description:
 * @author: Mr.Wang
 * @create: 2022-01-11 15:24
 **/
public class Print {
    CountDownLatch countDownLatch = new CountDownLatch(1);
    Lock lock = new ReentrantLock(true);
    volatile int num  = 0;
    public void printA() {
        lock.lock();
        try {
            num++;
            System.out.println("current Thread A:" + Thread.currentThread()+num);
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }
    public void count(){
        countDownLatch.countDown();
    }

    public void printB() {
        lock.lock();
        try {
            num++;
            System.out.println("current Thread B:" + Thread.currentThread()+num);
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        Print p = new Print();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    p.countDownLatch.await();
                }catch (Exception e){
                    e.printStackTrace();
                }
                for (int i = 0; i < 50; i++) {
                    p.printA();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                p.count();
                for (int i = 0; i < 50; i++) {
                    p.printB();
                }
            }
        }).start();
    }

注意这里我试用了公平锁,避免同一个线程多次获取锁的情况来实现顺序打印,同时使用

countDownLatch让两个线程同时开始

方法四: Condition

public class Print {
    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 volatile   static int count = 0;
    private  static int sum=1;

    static class ThreadA extends Thread {
        @Override
        public void run() {
            try {
                lock.lock();

                for (int i = 0; i < 10; i++) {
                    if (count % 3 != 0){//注意这里是不等于0,也就是说没轮到该线程执行,之前一直等待状态
                        A.await(); //该线程A将会释放lock锁,构造成节点加入等待队列并进入等待状态
                    }
                    System.out.println("-------第"+sum+"次--------");
                    System.out.println("A");
                    count++;
                    B.signal(); // A执行完唤醒B线程
                }

            } 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++) {
                    if (count % 3 != 1)
                        B.await();// B释放lock锁,当前面A线程执行后会通过B.signal()唤醒该线程
                    System.out.println("B");
                    count++;
                    C.signal();// B执行完唤醒C线程
                }
            } 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++) {
                    if (count % 3 != 2)
                        C.await();// C释放lock锁
                    System.out.println("C");
                    count++;
                    sum++;
                    A.signal();// C执行完唤醒A线程
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ThreadA().start();
        new ThreadB().start();
        new ThreadC().start();
    }
}
  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
### 回答1: Java多线程交替打印可以通过使用两个线程和一个共享变量来实现。假设我们需要交替打印数字1到100,其中一个线程负责打印奇数,另一个线程负责打印偶数。 首先,我们需要创建一个共享变量count,并初始化为1。然后,我们创建两个线程,分别为奇数线程和偶数线程。 奇数线程的任务是判断count的值是否小于等于100,如果是则打印count的值,并将count的值加1。然后,让偶数线程继续执行。 偶数线程的任务也是判断count的值是否小于等于100,如果是则打印count的值,并将count的值加1。然后,让奇数线程继续执行。 整个过程会一直进行下去,直到count的值大于100为止。 下面是具体实现的Java代码: ```java public class AlternatePrinting { private static volatile int count = 1; private static Object lock = new Object(); public static void main(String[] args) { Thread oddThread = new Thread(new PrintOdd()); Thread evenThread = new Thread(new PrintEven()); oddThread.start(); evenThread.start(); } static class PrintOdd implements Runnable { @Override public void run() { while (count <= 100) { synchronized (lock) { if (count % 2 != 0) { System.out.println(Thread.currentThread().getName() + ": " + count); count++; lock.notifyAll(); } else { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } static class PrintEven implements Runnable { @Override public void run() { while (count <= 100) { synchronized (lock) { if (count % 2 == 0) { System.out.println(Thread.currentThread().getName() + ": " + count); count++; lock.notifyAll(); } else { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } } ``` 上述代码中,使用了一个共享的锁对象lock来保证奇数线程和偶数线程之间的互斥和同步。同时,通过wait()和notifyAll()方法实现了线程的阻塞和唤醒操作。 通过以上代码,可以实现奇数和偶数的交替打印,输出结果类似如下: ``` Thread-0: 1 Thread-1: 2 Thread-0: 3 Thread-1: 4 ... Thread-0: 99 Thread-1: 100 ``` 这样就实现了Java多线程交替打印。 ### 回答2: Java多线程交替打印可以通过使用synchronized关键字和wait()、notify()、notifyAll()方法来实现。 首先,可以创建一个共享的对象作为锁,例如可以使用一个Object对象。 然后,创建两个线程,一个线程负责打印奇数,另一个线程负责打印偶数。在这两个线程的run()方法中,使用synchronized关键字来锁住共享对象。通过使用while循环来判断当前的数字是否满足打印条件,如果不满足则调用wait()方法等待;如果满足则打印数字并使用notify()方法唤醒其他线程。 在主线程中,使用start()方法启动这两个线程,并使用Thread.sleep()方法来控制每次打印的间隔时间。 具体实现如下: ``` public class AlternatePrinting { private static final Object lock = new Object(); private static int number = 1; public static void main(String[] args) { Thread oddThread = new Thread(() -> { while (number <= 10) { synchronized (lock) { if (number % 2 == 1) { System.out.println("奇数线程:" + number++); lock.notify(); } else { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }); Thread evenThread = new Thread(() -> { while (number <= 10) { synchronized (lock) { if (number % 2 == 0) { System.out.println("偶数线程:" + number++); lock.notify(); } else { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }); oddThread.start(); evenThread.start(); } } ``` 上述代码会创建两个线程,一个线程负责打印奇数,另一个线程负责打印偶数。在主线程中启动这两个线程,程序会交替打印奇数和偶数直到数字达到10为止。 ### 回答3: Java中,实现多线程交替打印可以使用两种方法:一是使用synchronized关键字,二是使用Lock和Condition接口。 方法一:使用synchronized关键字 首先,定义一个变量flag作为线程间的通信标志。然后,创建两个线程,分别使用synchronized锁住共享资源并通过wait()和notify()方法交替进行打印。具体步骤如下: 1. 创建一个实现Runnable接口的类,重写run()方法。 2. 在run()方法中,使用synchronized锁住共享资源。 3. 使用while循环,判断flag的值。若flag为true,则调用wait()方法等待,否则进行打印。 4. 打印完后,将flag的值取反,并使用notify()方法唤醒其他线程。 5. 在main()方法中,创建两个线程对象,分别调用start()方法启动线程。 方法二:使用Lock和Condition接口 这种方式使用Lock接口来锁住共享资源,并使用Condition接口的await()和signal()方法来实现线程间的交替打印。具体步骤如下: 1. 创建一个实现Runnable接口的类,重写run()方法。 2. 在run()方法中,使用Lock接口的lock()方法锁住共享资源。 3. 使用while循环,判断flag的值。若flag为true,则调用Condition接口的await()方法等待,否则进行打印。 4. 打印完后,将flag的值取反,并使用Condition接口的signal()方法唤醒其他线程。 5. 在main()方法中,创建一个ReentrantLock对象和两个Condition对象,分别调用lock()方法和newCondition()方法初始化。 6. 创建两个线程对象,分别调用start()方法启动线程。 这两种方法都可以实现多线程交替打印,具体选择哪种方式取决于具体的需求和场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沉默终止

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值