java多线程 典型案例:子线程执行10次,主线程执行100次,两者交替50次
2016-04-09 17:10
423 查看
public class Test {
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable() {
public void run() {
for (int i = 1; i <= 50; i++) {
business.sub(i);
}
}
}).start();
for (int i = 1; i <= 50; i++) {
business.main(i);
}
}
}
class Business {
private boolean bShouldSub = true;
public synchronized void sub(int i) {
// 如果bussiness调用sub的话,则【!bShouldSub =false,bShouldSub=true】;
// 然后主线程main为等待,执行完sub后就bShouldSub=false;唤醒主线程main。
while (!bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("sub thread sequence of " + j + ",loop of " + i);
}
bShouldSub = false;
// 唤醒main
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("main thread sequence of " + j + ",loop of " + i);
}
bShouldSub = true;
// 唤醒sub
this.notify();
}
}
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable() {
public void run() {
for (int i = 1; i <= 50; i++) {
business.sub(i);
}
}
}).start();
for (int i = 1; i <= 50; i++) {
business.main(i);
}
}
}
class Business {
private boolean bShouldSub = true;
public synchronized void sub(int i) {
// 如果bussiness调用sub的话,则【!bShouldSub =false,bShouldSub=true】;
// 然后主线程main为等待,执行完sub后就bShouldSub=false;唤醒主线程main。
while (!bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("sub thread sequence of " + j + ",loop of " + i);
}
bShouldSub = false;
// 唤醒main
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("main thread sequence of " + j + ",loop of " + i);
}
bShouldSub = true;
// 唤醒sub
this.notify();
}
}
相关文章推荐
- hdu2025java字符题
- java学习第八天
- Java获取项目相对 绝对路径
- 260. Single Number III
- jdk版本间区别
- springAOP配置文件
- 获取java项目的根目录-方法大全
- JAVA基础--日期处理
- 使用Java语言编写一款日记软件
- Java 爬虫 菜逼教程 00
- 深入理解Java虚拟机读书笔记
- 关于利用动态代理手写数据库连接池的异常 java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to java.sql.Connection
- Dijsktra算法原理介绍及java源码实践
- 单例模式几种实现方式
- Java中普通代码块,构造代码块,静态代码块区别及代码示例(转自sophine)
- JAVA框架之Hibernate【Hibernate缓存详解】
- 第八章:Shiro和Spring的集成
- 归并排序_java实现
- Java并发编程:同步容器
- 关于java堆内存溢出的几种情况