一个很有意思的题目,网上看到的,自己写了一下
题目的大概意思就是:
主线程中, 子线程运行5次
子线程循环5次之后主线程循环10次为一个周期,一次循环50次
/**
* TraditionalSynchThread.java V1.0 Apr 28, 2012 1:13:18 PM
*
* Copyright Lizhenbin Co. ,Ltd. All rights reserved.
*
* Modification history(By Time Reason):
*
* Description:
*/
package com.lzb.common;
/**
*
* 功能描述:线程的同步互斥,以及通信
*
* @author lizhenbin
*
* <p>修改历史:(修改人,修改时间,修改原因/内容)</p>
*/
public class TraditionalSynchThread implements Runnable {
private static Resource r = new Resource();
public void run() {
/**
* 主线程中, 子线程运行5次
*/
new Thread(new Runnable(){
public void run() {
/**
* 子线程循环5次之后主线程循环10次为一个周期,一次循环50次
*/
for(int i=0; i<=10; i++) {
r.childMethod(i);
}
}
}).start();
/**
* 子线程循环5次之后主线程循环10次为一个周期,一次循环50次
*/
for(int i=0; i<10; i++) {
r.mainMethod(i);
}
}
}
/**
*
* 功能描述:同步互斥同步资源
*
* @author lizhenbin
*
* <p>修改历史:(修改人,修改时间,修改原因/内容)</p>
*/
class Resource {
private boolean isRunning = true;
private static final Integer c_times = 2;
private static final Integer m_times = 5;
/**
*
* 功能描述:子线程运行程序
*
* @author lizhenbin
* <p>创建日期 :Apr 28, 2012 2:30:08 PM</p>
*
* @param times
*
* <p>修改历史 :(修改人,修改时间,修改原因/内容)</p>
*/
public synchronized void childMethod(int times) {
while(!isRunning) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* 子线程循环c_times次
*/
for(int i=1; i<=c_times; i++) {
System.out.println("--->子线程执行" + i + "次,-----循环第" + times + "次");
}
}
isRunning = false;
this.notify();
}
public synchronized void mainMethod(int times) {
while(isRunning) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* 子线程循环m_times次
*/
for(int i=1; i<=m_times; i++) {
System.out.println("主线程执行" + i + "次,----循环第" + times + "次<-----");
}
}
isRunning = true;
this.notify();
}
}