子线程和 主线程 互换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | package demo; /** * 子线程循环5次,主线程循环10次。依次交替。整个交替循环3次 * */ public class ThreadTest { public static void main(String[] args) { init(); } static void init(){ final Print p = new Print(); //封装了 循环的动作 new Thread( new Runnable(){ @Override public void run() { for ( int i= 0 ;i< 3 ;i++){ p.subPrint( 5 ); //循环5次 } } }).start(); new Thread( new Runnable(){ @Override public void run() { for ( int i= 0 ;i< 3 ;i++){ p.mainPrint( 10 ); //循环10次 } } }).start(); } } |
Print:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | package demo; /** * 两个方法之间互斥 (方法里面完整执行完),用 Sflag实现 开关控制 两个方法的切换 * */ public class Print { boolean Sflag = true ; public synchronized void subPrint( int num){ while (!Sflag){ //避免 伪唤醒 try { this .wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for ( int i= 1 ;i<=num;i++){ System.out.println(Thread.currentThread().getName()+ ":" +i); } Sflag = false ; this .notifyAll(); } public synchronized void mainPrint( int num){ while (Sflag){ try { this .wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for ( int i= 1 ;i<=num;i++){ System.out.println(Thread.currentThread().getName()+ ":" +i); } Sflag = true ; this .notifyAll(); } } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步