zoukankan      html  css  js  c++  java
  • 线程互斥通信

    1.子线程运行10次,主线程运行20次,接着回到子线程10次,然后在是主线程20次,如此循环10次。

    ** 当要用到共同数据(包括同步锁)的若干方法应当放在同一个类当中,体现了程序的高类聚,和健壮性。
    public class Test{
    public static void main(String[] args) {
    final Business business = new Business();
    new Thread(new Runnable() {
    public void run() {
    for(int i=1;i<=10;i++){
    business.son();
    }
    }
    }).start();

    for(int i=1;i<=10;i++){
    business.main();
    }
    }
    }

    class Business{
    boolean b = true;
    public synchronized void son(){
    while(!b){
    try {
    this.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    for(int j = 1;j<=10;j++){
    System.out.println("son=>"+j);
    }

    b = false;
    this.notify();
    }

    public synchronized void main(){
    while (b) {
    try {
    this.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    for(int j = 1;j<=20;j++){
    System.out.println("main=>"+j);
    }

    b = true;
    this.notify();
    }
    }

  • 相关阅读:
    Java第九次作业
    Java第八次作业
    Java第七次作业
    Java第六次作业
    Java第五次作业
    Java第四次作业
    Java第三次作业
    Java第二次作业
    Java第一次作业
    高级工程师和初级工程师之间的一道坎
  • 原文地址:https://www.cnblogs.com/dsking/p/5256281.html
Copyright © 2011-2022 走看看