黑马程序员技术交流社区
标题:
线程间通讯
[打印本页]
作者:
fmi110
时间:
2015-9-30 16:01
标题:
线程间通讯
线程间同通讯主要用于协调线程之间执行顺序,即线程A处理完一件事后,通知B线程处理。也就是说要打破线程之间获取cpu执行权的随机性。要实现这种方法,就需要用查询法,当A或的执行权时,
查询是否该自己运行(用一个变量来指示),不是则进入阻塞状态,并释放执行权。
为了方便实现,线程A B能访问的事同一变量(指示运行的变量),可将线程的执行内容都封装到同一个类中的方法里
在线程里通过run方法来调用该方法,而不是直接将任务代码放到run中
这种设计方法,能更容易实现同步和通讯
package test;
public class Test2 {
public static void main(String[] args) throws Exception{
final P p = new P();
new Thread() {
public void run() {
for (int i = 1; i < 11; i++) {
try {
p.show(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}.start();
new Thread() {
public void run() {
for (int i = 1; i < 11; i++) {
try {
p.print(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}.start();
}
}
class P {
boolean flag = false;
public synchronized void show(int i) throws InterruptedException {
while (flag)
this.wait();
System.out.println(i + "..." + Thread.currentThread().getName());
flag = true;
this.notifyAll();
}
public synchronized void print(int i) throws InterruptedException {
while (!flag)
this.wait();
System.out.println(i + "..." + Thread.currentThread().getName());
flag = false;
this.notifyAll();
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2