首页 > 编程语言 > 详细

主子、线程切换

时间:2019-07-07 00:29:14      阅读:144      评论:0      收藏:0      [点我收藏+]

最近看到一多线程题目,觉得很有意义,虽然业务中尚未出现过,但保不定以后会用到。

题目:编程主线程循环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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!