[one_demo_17]使用传统方式实现线程间通信的例子
题目: 子线程循环10次,接着到主线程循环10次;接着又回到子线程循环10次,接着又到主线程循环10次,如此循环50次。
使用Object的wait()和notify()方法实现。
Java代码
第一种,不使用面向对象的思想实现
/**
* 练习线程间通信
*
* @author Administrator
*
*/
public class ThreadCommunicationOld {
// 锁
private static String lock = "lock";
// 线程间通信的开关
private static boolean isSub = true;
public static void main(String[] args) {
// 子线程
new Thread(new Runnable() {
public void run() {
// 循环50次
for (int i = 0; i < 50; i++) {
// 加锁
synchronized (lock) {
// 如果不是子线程状态,就让子线程阻塞
if (!isSub) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 执行任务10次
for (int j = 0; j < 10; j++) {
System.out.println("sub thread sequence of " + j + ", loop of " + i);
}
// 执行完任务后,调整为非子线程状态
isSub = false;
// 唤醒主线程
lock.notify();
}
}
}
}).start();
// 主线程,执行50次
for (int i = 0; i < 50; i++) {
// 主线程加锁
synchronized (lock) {
// 判断是否为子线程状态,如果是子线程状态,就让主线程阻塞
if (isSub) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 执行任务10次
for (int j = 0; j < 10; j++) {
System.out.println("main thread sequence of " + j + ", loop of " + i);
}
// 调整为子线程状态
isSub = true;
// 唤醒子线程
lock.notify();
}
}
}
}
第二种,使用面向对象的思想,将执行的业务放在一个业务类中,在这个业务类中,将执行的方法加上同步;另外,在判断线程状态时使用while取代if,防止出现假唤醒,也就是每次拿到锁后,都要判断状态。
/**
* 练习线程间通信 题目: 子线程循环10次,接着到主线程循环100次;接着又回到子线程循环10次,接着又到主线程循环100次,如此循环50次
*
* @author Administrator
*
*/
public class ThreadCommunicationOld2 {
public static void main(String[] args) {
// 创建业务对象
final Business business = new Business();
// 子线程
new Thread(new Runnable() {
public void run() {
// 循环50次
for (int i = 0; i < 50; i++) {
// 子线程业务
business.sub(i);
}
}
}).start();
// 主线程,执行50次
for (int i = 0; i < 50; i++) {
// 主线程业务
business.main(i);
}
}
}
// 将主线程或者子线程的业务交给业务类管理,更加的面向对象
class Business {
// 线程状态标识
private boolean isSub = true;
// 主线程业务
public synchronized void main(int i) {
// 判断是否为子线程状态,如果是子线程状态,就让主线程阻塞
while (isSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 执行任务10次
for (int j = 0; j < 10; j++) {
System.out.println("main thread sequence of " + j + ", loop of " + i);
}
// 调整为子线程状态
isSub = true;
// 唤醒子线程
this.notify();
}
// 子线程业务
public synchronized void sub(int i) {
// 如果不是子线程状态,就让子线程阻塞
while (!isSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 执行任务10次
for (int j = 0; j < 10; j++) {
System.out.println("sub thread sequence of " + j + ", loop of " + i);
}
// 执行完任务后,调整为非子线程状态
isSub = false;
// 唤醒主线程
this.notify();
}
}