zoukankan      html  css  js  c++  java
  • 线程:子线程先循环十次,主线程在循环20次,再子线程循环十次,主线程循环20次,如此循环50次

    
    
    子线程先循环十次,主线程在循环20次,再子线程循环十次,主线程循环20次,如此循环50次

    1
    /** 2 * 子线程先循环十次,主线程在循环20次,再子线程循环十次,主线程循环20次,如此循环50次 3 * @author llj 4 * 5 */ 6 public class ThreadTest { 7 8 public static void main(String[] args) { 9 Syn syn = new Syn(); 10 new Thread(new Runnable() { 11 @Override 12 public void run() { 13 for(int i=0; i<50; i++) { 14 syn.child(); 15 } 16 } 17 }).start(); 18 for(int i=0; i<50; i++) { 19 syn.main(); 20 } 21 } 22 } 23 24 class Syn{ 25 private boolean temp = true; 26 public synchronized void main() { 27 if(temp) { 28 try { 29 this.wait();//导致当前线程等待,直到另一个线程调用该对象的 notify()方法或 notifyAll()方法 30 } catch (InterruptedException e) { 31 e.printStackTrace(); 32 } 33 } 34 for(int i=0; i<20; i++) { 35 System.out.println("主线程"+i); 36 } 37 temp = true; 38 this.notify();//唤醒正在等待对象监视器的单个线程。 39 } 40 public synchronized void child() { 41 if(!temp) { 42 try { 43 this.wait(); 44 } catch (InterruptedException e) { 45 e.printStackTrace(); 46 } 47 } 48 for(int j=0; j<10; j++) { 49 System.out.println("子线程"+j); 50 } 51 temp = false; 52 this.notify(); 53 } 54 }
  • 相关阅读:
    linux下tomcat之too many open files
    oracle之Io异常: Got minus one from a read call
    oracle监听模块异常
    面向对象分析与面向结构分析
    jdbc连接oracle出现ORA-12505错误
    git命令行入门
    oracle之远程数据投毒漏洞(CVE-2012-1675)修复
    sql盲注
    springboot日志配置Logback
    Java 多线程 重入锁
  • 原文地址:https://www.cnblogs.com/lenglangjin/p/11025665.html
Copyright © 2011-2022 走看看