Java 多线程习题(一):用两个线程,一个输出字母,一个输出数字, 交替输出1A2B3C4D5E6F

//方法一 LockSupport
    static Thread t1 = null;
    static Thread t2 = null;

    char[] char1 = "123456".toCharArray();
    char[] char2 = "ABCDEF".toCharArray();

    t1 = new Thread(() -> {
        for (char c : char1) {
            System.out.println(c);
            LockSupport.unpark(t2);//叫醒
            LockSupport.park();//阻塞
        }
    }, "t1");

    t2 = new Thread(() -> {
        for (char c : char2) {
            LockSupport.park();
            System.out.println(c);
            LockSupport.unpark(t1);
        }
    }, "t2");
    t1.start();
    t2.start();

//方法二 synchronized
    char[] char1 = "123456".toCharArray();
    char[] char2 = "ABCDEF".toCharArray();
    
    Object o = new Object();
    
    new Thread(() -> {
        synchronized (o) {
            for (char c : char1) {
                System.out.println(c);
                try {
                    o.notify();//不保证叫醒的是想叫醒的线程
                    o.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            o.notify();
        }
    }, "t1").start();


    new Thread(() -> {
        synchronized (o) {
            for (char c : char2) {
                System.out.println(c);
                try {
                    o.notify();
                    o.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            o.notify();
        }
    }, "t2").start();
//方法三 ReentrantLock  代替synchronized  因为ReentrantLock可以多个队列,synchronized只有一个队列
   ReentrantLock lock = new ReentrantLock();

   Condition conditionT1 = lock.newCondition();
   Condition conditionT2 = lock.newCondition();

   CountDownLatch latch = new CountDownLatch(1);

   new Thread(() -> {
       try {
           latch.await();
       } catch (InterruptedException e) {
           throw new RuntimeException(e);
       }
       lock.lock();
       try {
           for (char c : char2) {
               System.out.println(c);
               conditionT2.signal();//叫醒
               conditionT1.await();
           }
           conditionT2.signal();
       } catch (InterruptedException e) {
           throw new RuntimeException(e);
       } finally {
           lock.unlock();
       }
   }, "t1").start();

   new Thread(() -> {
       lock.lock();
       try {
           for (char c : char1) {
               System.out.println(c);
               latch.countDown();
               conditionT1.signal();
               conditionT2.await();
           }
           conditionT1.signal();
       } catch (InterruptedException e) {
           throw new RuntimeException(e);
       } finally {
           lock.unlock();
       }
   }, "t2").start();
//方法四 LinkedTransferQueue
    LinkedTransferQueue<Object> queue = new LinkedTransferQueue<>();

    new Thread(() -> {
        try {
            for (char c : char1) {
                queue.transfer(c);
                System.out.println(queue.take());
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }, "t1").start();

    new Thread(() -> {

        try {
            for (char c : char2) {
                //从容器里拿一个字符出来,并把该字符打印出来
                System.out.println(queue.take());
                //向容器送字符
                queue.transfer(c);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }, "t2").start();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,我们可以使用 `synchronized` 关键字和 `wait()`、`notify()` 方法来实现线程交替输出。下面是一个示例代码: ```java class OddEvenPrinter { private int count; private int maxCount; public OddEvenPrinter(int maxCount) { this.maxCount = maxCount; this.count = 1; } public synchronized void printOdd() throws InterruptedException { while (count <= maxCount) { if (count % 2 != 0) { System.out.println(count); count++; notify(); } else { wait(); } } } public synchronized void printEven() throws InterruptedException { while (count <= maxCount) { if (count % 2 == 0) { System.out.println(count); count++; notify(); } else { wait(); } } } } public class Main { public static void main(String[] args) { OddEvenPrinter printer = new OddEvenPrinter(100); Thread oddThread = new Thread(() -> { try { printer.printOdd(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread evenThread = new Thread(() -> { try { printer.printEven(); } catch (InterruptedException e) { e.printStackTrace(); } }); oddThread.start(); evenThread.start(); } } ``` 在这个代码中,我们创建了一个名为 `OddEvenPrinter` 的类,它有一个 `count` 变量来表示当前要输出数字,和一个 `maxCount` 变量来表示最大的数字。`printOdd()` 方法用于输出奇数,`printEven()` 方法用于输出偶数。 在每个方法中,我们使用 `synchronized` 关键字来确保线程的同步。在 `printOdd()` 方法中,当 `count` 为奇数时输出数字并递增,然后调用 `notify()` 方法唤醒等待的线程;如果 `count` 为偶数,则调用 `wait()` 方法使线程等待。在 `printEven()` 方法中同理。 在 `main()` 方法中,我们创建了两个线程 `oddThread` 和 `evenThread`,分别执行 `printOdd()` 和 `printEven()` 方法。然后启动这两个线程,它们将交替输出奇偶数。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值