java 线程同步 notify wait

来源:互联网 发布:用友u8数据库表结构 编辑:程序博客网 时间:2024/05/01 02:23

子线程循环10次,主线程循环100次。接着子线程循环10次,主线程循环100次。如此循环50次。摘自张孝祥老师线程视频源码

package test;public class Test {// 子线程循环10次,主线程循环100次。接着子线程循环10次,主线程循环100次。如此循环50次public static void main(String[] args) {new Test().init();}private void init() {final Business business = new Business();new Thread() {public void run() {for (int i = 1; i <= 10; i++) {business.subdo();// 子线程}};}.start();for (int i = 1; i <= 10; i++) {//business.subdo();// 子线程business.maindo();}}class Business {private boolean isShouldSub = true;public void subdo() {synchronized (Test.class) {if (!isShouldSub) {// 如果不该子线程执行try {Test.class.wait();} catch (InterruptedException e) {e.printStackTrace();}}for (int i = 1; i <= 10; i++) {System.out.println(Thread.currentThread().getName()+ " running .." + "  " + i + "次");}isShouldSub=false;Test.class.notifyAll();}}public void maindo() {synchronized (Test.class) {if (isShouldSub) {try {Test.class.wait();} catch (InterruptedException e) {e.printStackTrace();}}for (int i = 1; i <= 20; i++) {System.out.println(Thread.currentThread().getName()+ " running .." + "  " + i + "次");}isShouldSub=true;Test.class.notifyAll();}}}}





0 0
原创粉丝点击