最近看到一多线程题目,觉得很有意义,虽然业务中尚未出现过,但保不定以后会用到。
题目:编程主线程循环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 }
原文:https://www.cnblogs.com/shaozhen/p/11144625.html