首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

线程考试题

2012-12-27 
线程试题package com.test.thread/** * 子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,

线程试题
package com.test.thread;

/**
* 子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次, 接着再回到主线程循环100次;如此循环50次。
*
* @author yhd2
*
*/
public class Test {
public static void main(String[] args) {
new Test().init();
}

private void init() {
final Bussiness buss = new Bussiness();
//子线程
new Thread() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
buss.sub(i + 1);
}
}

}.start();
//主线程
for (int i = 0; i < 50; i++) {
buss.main(i + 1);
}
}
}

class Bussiness {
private boolean flag = true;

public synchronized void sub(int seq) {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
System.out.println("sub sequence of " + seq + " loop for " + i);
}
flag = false;
this.notify();
}

public synchronized void main(int seq) {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 100; i++) {
System.out.println("main sequence of " + seq + " loop for " + i);
}
flag = true;
this.notify();
}
}

热点排行