黑马程序员技术交流社区
标题:
Thread问题
[打印本页]
作者:
liumeng
时间:
2012-3-23 07:51
标题:
Thread问题
public class TestThread1 {
/**
* @param args
*/
public static void main(String[] args) {
final printChar business = new printChar();
new Thread(
new Runnable() {
@Override
public void run() {
for(int i=1;i<=20;i++){
business.sub1(i);
}
}
}
).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=1;i<=20;i++){
business.sub2(i);
}
}
}
class printChar {
private boolean bShouldSub1 = true;
public synchronized void sub1(int i){
while(!bShouldSub1){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=2;j++){
System.out.print("a");
}
bShouldSub1 = false;
this.notify();
}
public synchronized void sub2(int i){
while(bShouldSub1){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("b");
bShouldSub1 = true;
this.notify();
}
}
如果调用notify 但没有wait的线程怎么不会出错了
作者:
liumeng
时间:
2012-3-23 08:01
是不是只有调用WAIT方法时才会调用notify呢
作者:
OMG
时间:
2012-3-23 09:36
notify方法,是唤醒线程池中的第一个等待线程,如果没有线程,对程序运行没影响,所以是多余,不是错误;
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2