通过wait和notify实现多线程交替执行,话不多说,直接撸代码! 主线程和子线程交替执行 public class TranditionalThreadSynchrized { public static void main(String[] args){ final Business business; business = new Business(); //子线程执行 new Thread(new Runnable() { @Override public void run() { for(int i=1; i<=10; i++){ business.sub(i); } } }).start(); //主线程执行 for(int i=1; i<=10; i++){ business.main(i); } } static class Business{ boolean isExecute = true; //子线程执行逻辑 public synchronized void sub(int i){ if(isExecute){ for (int j=1; j<=5; j++){ System.out.println("sub execute " + j + " loop of " + i); } isExecute = false; this.notify(); } else try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } //主线程执行逻辑 public synchronized void main(int i){ if(!isExecute){ for (int j=1; j<=5; j++){ System.out.println("main execute " + j + " loop of " + i); } isExecute = true; this.notify(); } else try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
java多线程通信
最新推荐文章于 2025-12-02 18:57:44 发布
3783

被折叠的 条评论
为什么被折叠?



