交替打印-Interleaving

打印 上一主题 下一主题

主题 1638|帖子 1638|积分 4914

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
目录

交替打印奇偶数

标题概述

创建两个线程,一个打印奇数,一个打印偶数。要求两个线程交替输出,顺序打印出 1 2 3 4 5 ... 100。
解法一:synchronized + wait/notify
  1. public class Main {
  2.     private static final Object lock = new Object();
  3.     private static int count = 1;
  4.     public static void main(String[] args) {
  5.         Thread odd = new Thread(() -> {
  6.             while (count <= 100) {
  7.                 synchronized (lock) {
  8.                     if ((count & 1) == 0) {
  9.                         try {
  10.                             lock.wait();
  11.                         } catch (InterruptedException e) {
  12.                             e.printStackTrace();
  13.                         }
  14.                     } else {
  15.                         System.out.println(Thread.currentThread().getName() + ": " + count);
  16.                         count++;
  17.                         lock.notify();
  18.                     }
  19.                 }
  20.             }
  21.         }, "ODD");
  22.         Thread even = new Thread(() -> {
  23.            while (count <= 100) {
  24.                synchronized (lock) {
  25.                    if ((count & 1) == 1) {
  26.                        try {
  27.                            lock.wait();
  28.                        } catch (InterruptedException e) {
  29.                            e.printStackTrace();
  30.                        }
  31.                    } else {
  32.                        System.out.println(Thread.currentThread().getName() + ": " + count);
  33.                        count++;
  34.                        lock.notify();
  35.                    }
  36.                }
  37.            }
  38.         }, "EVEN");
  39.         odd.start();
  40.         even.start();
  41.     }
  42. }
复制代码
交替打印ABC

标题概述

创建三个线程,分别打印 "A"、"B"、"C",要求按顺序交替输出 ABCABC...,共打印 10 次。
解法一:synchronized + wait/notify
  1. import java.util.concurrent.Semaphore;
  2. public class Main {
  3.     static int count = 1;
  4.     static Semaphore oddSemaphore = new Semaphore(1);
  5.     static Semaphore evenSemaphore = new Semaphore(0);
  6.     public static void main(String[] args) {
  7.         new Thread(() -> {
  8.             while (count <= 100) {
  9.                 try {
  10.                     oddSemaphore.acquire();
  11.                     if (count > 100) break;
  12.                     System.out.println(("ODD : " + count++));
  13.                     evenSemaphore.release();
  14.                 } catch (InterruptedException e) {
  15.                     e.printStackTrace();
  16.                 }
  17.             }
  18.         }).start();
  19.         new Thread(() -> {
  20.             while (count <= 100) {
  21.                 try {
  22.                     evenSemaphore.acquire();
  23.                     if (count > 100) break;
  24.                     System.out.println(("EVEN : " + count++));
  25.                     oddSemaphore.release();
  26.                 } catch (InterruptedException e) {
  27.                     e.printStackTrace();
  28.                 }
  29.             }
  30.         }).start();
  31.     }
  32. }
复制代码
解法二:ReentrantLock + Condition
  1. public class Main {
  2.     private static int state = 0;
  3.     private static final Object lock = new Object();
  4.     public static void main(String[] args) {
  5.         int loop = 10;
  6.         new Thread(() -> printLetter('A', 0, 10)).start();
  7.         new Thread(() -> printLetter('B', 1, 10)).start();
  8.         new Thread(() -> printLetter('C', 2, 10)).start();
  9.     }
  10.     private static void printLetter(char ch, int target, int loop) {
  11.         for (int i = 0; i < loop;) {
  12.             synchronized (lock) {
  13.                 if (state != target) {
  14.                     try {
  15.                         lock.wait();
  16.                     } catch (InterruptedException e) {
  17.                         e.printStackTrace();
  18.                     }
  19.                 } else {
  20.                     System.out.println(ch);
  21.                     state = (state + 1) % 3;
  22.                     lock.notifyAll();
  23.                     i++;
  24.                 }
  25.             }
  26.         }
  27.     }
  28. }
复制代码
交替打印数字

标题概述

用3个线程打印 1~100 的整数,要求3个线程按顺序轮流打印
解法一:synchronized + wait/notify
  1. import java.util.concurrent.locks.*;
  2. public class Main {
  3.     private static int state = 0;
  4.     private static final Lock lock = new ReentrantLock();
  5.     private static final Condition A = lock.newCondition();
  6.     private static final Condition B = lock.newCondition();
  7.     private static final Condition C = lock.newCondition();
  8.     public static void main(String[] args) {
  9.         int loop = 10;
  10.         new Thread(() -> print('A', 0, A, B, loop)).start();
  11.         new Thread(() -> print('B', 1, B, C, loop)).start();
  12.         new Thread(() -> print('C', 2, C, A, loop)).start();
  13.     }
  14.     private static void print(char ch, int target, Condition curr, Condition next, int loop) {
  15.         for (int i = 0; i < loop;) {
  16.             lock.lock();
  17.             try {
  18.                 while (state != target) {
  19.                     curr.await();
  20.                 }
  21.                 System.out.println(ch);
  22.                 state = (state + 1) % 3;
  23.                 i++;
  24.                 next.signal();
  25.             } catch (InterruptedException e) {
  26.                 e.printStackTrace();
  27.             } finally {
  28.                 lock.unlock();
  29.             }
  30.         }
  31.     }
  32. }
复制代码
解法二:ReentrantLock + Condition
  1. public class Main {
  2.     private static int count = 1;
  3.     private static final Object lock = new Object();
  4.     public static void main(String[] args) {
  5.         for (int i = 0; i < 3; i++) {
  6.             int id = i;
  7.             new Thread(() -> {
  8.                 while (true) {
  9.                     synchronized (lock) {
  10.                         if (count > 100) break;
  11.                         if (count % 3 != id) {
  12.                             try {
  13.                                 lock.wait();
  14.                             } catch (InterruptedException e) {
  15.                                 e.printStackTrace();
  16.                             }
  17.                         } else {
  18.                             System.out.println(count++);
  19.                             lock.notifyAll();
  20.                         }
  21.                     }
  22.                 }
  23.             }).start();
  24.         }
  25.     }
  26. }
复制代码
总结与思考


  • 用while (true)
  • 及时开释锁制止死锁

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

卖不甜枣

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表