日期:2014-05-20  浏览次数:20741 次

java 线程相关 求解释 【问题都在注释里】
package thread;

//写两个线程,一个线程打印 1~52,另一个线程打印字母a-z。打印顺序为12a34b56c……5152z。要求用线程间的通信。
public class Thread_Wait_Notifyall {
public static void main(String[] args) {
Print p=new Print();
Thread t1=new NumberPrint(p);
Thread t2=new CharPrint(p);
t1.start();
t2.start();
}
}

class Print{
public int index=1;
public synchronized void print(int i){
if (index%3==0) {
try {
this.wait();//锁定当前线程?  这里锁定线程,唤醒之后,会继续执行下面的输出,对吗?如果是这样,就解释了下面为什么不可以用else
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//下面这3句为什么不可以放在else里面? 我试了 如果放在else里面  输出的数据不完整
System.out.print(" "+i);
index++;
//this.notifyAll();//这句是唤醒了所有的线程吗?
this.notify();  //notify也可以实现,那么这句又是唤醒了哪一个线程呢?是另一个线程吗?
}

public synchronized void print(char c){
if (index%3!=0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(" "+c);
index++;
//notifyAll();
this.notify();
}
}

class NumberPrint extends Thread{
private Print print=new Print();
public void run(){
for (int i = 1; i <= 52; i++) {
print.print(i);
}
}
public NumberPrint(Print print){
this.print=print;
}
}


class CharPrint extends Thread{
private Print print=new Print();
public void run(){
for (char c = 'a'; c < 'z'; c++) {
print.print(c);
}
}
public CharPrint(Print print){
this.print=print;
}
}

------解决方案--------------------
唤醒之后,会继续执行下面的输出;
notifyAll()和notify建议楼主看一下API,说得很清楚;
另外关于wait的用法,建议用while,不要用if;
看API上wait方法的示例:
synchronized (obj) {
 while (<condition does not hold>)
 obj.wait();
 ... // Perform action appropriate to condition
 }