`

线程试题

 
阅读更多
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();
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics