传统线程同步通信技术
2015-10-26 20:32
423 查看
public class TraditionalThreadCommunication {
/**
* 题目:
* 子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,
* 接着在回到主线程循环100次,如此循环50次
*
* 先实现线程互斥然后实现线程的等待和唤醒
* @param args
*/
public static void main(String[] args) {
final ThreadUtil threadUtil = new ThreadUtil();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 50; i++) {
threadUtil.subThread(i);
}
}
}).start();
for (int i = 0; i <= 50; i++) {
threadUtil.mainThread(i);
}
}
}
class ThreadUtil{
boolean isWait = true;
public synchronized void subThread(int i){
if (!isWait) {
try {
this.wait();//等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("zi"+j+"循环次数"+i);
}
isWait = false;
this.notify();//唤醒
}
public synchronized void mainThread(int i){
if (isWait) {
try {
this.wait();//等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 100; j++) {
System.out.println("main"+j+"循环次数"+i);
}
isWait = true;
this.notify();//唤醒
}
}
/**
* 题目:
* 子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,
* 接着在回到主线程循环100次,如此循环50次
*
* 先实现线程互斥然后实现线程的等待和唤醒
* @param args
*/
public static void main(String[] args) {
final ThreadUtil threadUtil = new ThreadUtil();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 50; i++) {
threadUtil.subThread(i);
}
}
}).start();
for (int i = 0; i <= 50; i++) {
threadUtil.mainThread(i);
}
}
}
class ThreadUtil{
boolean isWait = true;
public synchronized void subThread(int i){
if (!isWait) {
try {
this.wait();//等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("zi"+j+"循环次数"+i);
}
isWait = false;
this.notify();//唤醒
}
public synchronized void mainThread(int i){
if (isWait) {
try {
this.wait();//等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 100; j++) {
System.out.println("main"+j+"循环次数"+i);
}
isWait = true;
this.notify();//唤醒
}
}