您的位置:首页 > 其它

子线程循环10次 主线程循环100次 然后如此反复50次

2017-05-17 17:33 393 查看
package com.x.test;

/**
* @author lelonta
* @version 1.0
*/
public class ThreadCommunicate {

//子线程循环10次 主线程循环100次 然后如此反复50次
public static void main(String[] args) {

new ThreadCommunicate().init();

}

public void init() {

final business bun = new business();

new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 50; i++) {

bun.sub(i);

}
}
}) {

}.start();

new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 50; i++) {

bun.main(i);

}
}
}) {

}.start();

//本身main方法就是一个线程
//        for (int i = 1; i <= 50; i++) {
//
//            bun.main(i);
//
//        }

}

//内部类
class business {
//标识符
private boolean bShouldSub = true;

public synchronized void sub(int i) {

while (!bShouldSub) {

try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("子线程"+j+",循环次数"+i);
}
bShouldSub = false;
this.notify();
}

public synchronized void main(int i) {

while (bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

for (int j = 1; j <= 100; j++) {
System.out.println("主线程"+j+",循环次数"+i);
}
bShouldSub = true;
this.notify();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐