最近看到一多线程题目,觉得很有意义,虽然业务中尚未出现过,但保不定以后会用到。
题目:编程主线程循环20次,子线程循环10次,以此循环往复50次
1 public class Main { 2 // -1 双方均不运行, 0 主线程运行,1 子线程运行 3 static volatile int flag = -1; 4 static volatile int i = 0; 5 static volatile int mainCount = 1; 6 static volatile int childCount = 1; 7 8 public static void main(String[] args) throws Exception { 9 new Thread(() -> { 10 child(); 11 }).start(); 12 for (i = 0; i < 50; i++) { 13 if (flag < 0) { 14 // 通知子线程开始运行 15 flag = 1; 16 } 17 // cas检查标志位 18 while (true) { 19 if (flag == 0) { 20 System.out.println(mainCount++ + "main-" + i); 21 for(int t =0; t < 20;t++) {} 22 // 更换标志,切换子线程运行 23 flag = 1; 24 // 退出cas 25 break; 26 } 27 sleep(); 28 } 29 System.out.println("*********" + i + "*********"); 30 } 31 } 32 33 static void child() { 34 while (true) { 35 // 结束程序 36 if (i >= 50) { 37 break; 38 } 39 if (flag == -1 || flag == 0) { 40 sleep(); 41 } 42 System.out.println(childCount++ + "child-" + i); 43 for(int t =0; t < 10;t++) {} 44 // 更改标志,切换主线程运行 45 flag = 0; 46 sleep(); 47 } 48 } 49 50 static void sleep() { 51 try { 52 Thread.sleep(100); 53 } catch (Exception e) { 54 } 55 } 56 }
两个线程交互数据
1 public class Main { 2 static Object lock = new Object(); 3 static int n = 0; 4 5 public static void main(String[] args) { 6 new Thread() { 7 @Override 8 public void run() { 9 while (true) { 10 synchronized (lock) { 11 if (n < 1) { 12 try { 13 System.out.println("等待加酒"); 14 lock.wait(); 15 } catch (InterruptedException e) { 16 e.printStackTrace(); 17 } 18 } 19 System.out.println("喝杯酒 -1"); 20 n--; 21 try { 22 Thread.sleep(1000); 23 } catch (InterruptedException e) { 24 e.printStackTrace(); 25 } 26 lock.notifyAll(); 27 } 28 } 29 30 } 31 }.start(); 32 33 new Thread() { 34 @Override 35 public void run() { 36 while (true) { 37 synchronized (lock) { 38 if (n > 0) { 39 try { 40 lock.wait(); 41 } catch (InterruptedException e) { 42 e.printStackTrace(); 43 } 44 } else { 45 System.out.println("加杯酒 +1"); 46 n++; 47 try { 48 Thread.sleep(1000); 49 } catch (InterruptedException e) { 50 e.printStackTrace(); 51 } 52 lock.notifyAll(); 53 } 54 } 55 } 56 } 57 }.start(); 58 } 59 }
运行结果