多线程实现交替打印

力扣:交替打印 FooBar 

六种方式:


// BLOCKING Queue
public class FooBar {
    private int n;
    private BlockingQueue<Integer> bar = new LinkedBlockingQueue<>(1);
    private BlockingQueue<Integer> foo = new LinkedBlockingQueue<>(1);
    public FooBar(int n) {
        this.n = n;
    }
    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            foo.put(i);
            printFoo.run();
            bar.put(i);
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            bar.take();
            printBar.run();
            foo.take();
        }
    }
}

//CyclicBarrier 控制先后
class FooBar6 {
    private int n;

    public FooBar6(int n) {
        this.n = n;
    }

    CyclicBarrier cb = new CyclicBarrier(2);
    volatile boolean fin = true;

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            while(!fin);
            printFoo.run();
            fin = false;
            try {
                cb.await();
            } catch (BrokenBarrierException e) {}
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            try {
                cb.await();
            } catch (BrokenBarrierException e) {}
            printBar.run();
            fin = true;
        }
    }
}

// 自旋 + 让出CPU
class FooBar5 {
    private int n;

    public FooBar5(int n) {
        this.n = n;
    }

    volatile boolean permitFoo = true;

    public void foo(Runnable printFoo) throws InterruptedException {     
        for (int i = 0; i < n; ) {
            if(permitFoo) {
        	    printFoo.run();
            	i++;
            	permitFoo = false;
            }else{
                Thread.yield();
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {       
        for (int i = 0; i < n; ) {
            if(!permitFoo) {
        	printBar.run();
        	i++;
        	permitFoo = true;
            }else{
                Thread.yield();
            }
        }
    }
}



// 可重入锁 + Condition
class FooBar4 {
    private int n;

    public FooBar4(int n) {
        this.n = n;
    }
    Lock lock = new ReentrantLock(true);
    private final Condition foo = lock.newCondition();
    volatile boolean flag = true;
    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            lock.lock();
            try {
            	while(!flag) {
                    foo.await();
                }
                printFoo.run();
                flag = false;
                foo.signal();
            }finally {
            	lock.unlock();
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n;i++) {
            lock.lock();
            try {
            	while(flag) {
                    foo.await();
            	}
                printBar.run();
                flag = true;
                foo.signal();
            }finally {
            	lock.unlock();
            }
        }
    }
}

// synchronized + 标志位 + 唤醒
class FooBar3 {
    private int n;
    // 标志位,控制执行顺序,true执行printFoo,false执行printBar
    private volatile boolean type = true;
    private final Object foo=  new Object(); // 锁标志

    public FooBar3(int n) {
        this.n = n;
    }
    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            synchronized (foo) {
                while(!type){
                    foo.wait();
                }
                printFoo.run();
                type = false;
                foo.notifyAll();
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            synchronized (foo) {
                while(type){
                    foo.wait();
                }
                printBar.run();
                type = true;
                foo.notifyAll();
            }
        }
    }
}


// 信号量 适合控制顺序
class FooBar2 {
    private int n;
    private Semaphore foo = new Semaphore(1);
    private Semaphore bar = new Semaphore(0);
    public FooBar2(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            foo.acquire();
        	printFoo.run();
            bar.release();
        }
    }
    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            bar.acquire();
        	printBar.run();
            foo.release();
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答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()方法启动线程。 这两种方法都可以实现多线程交替打印,具体选择哪种方式取决于具体的需求和场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

愚人钊呀

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

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

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

打赏作者

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

抵扣说明:

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

余额充值