老师,我按照视频上老师的方法敲了代码,运行都没问题,但是突然发现,这个程序并没有自动结束,IDEAL中的红色方块一直亮着,如下图:
![]() |
麻烦老师帮忙看看是怎么回事,具体代码粘贴如下:
1.Printer类代码
package com.bjsxt.thread;
public class Printer {
private int index=1;//用于统计第几次打印
public synchronized void print(int number){
while(index%3==0){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(number);
index++;
super.notifyAll();//唤醒所有在printer这个对象上所有等待的线程
}
public synchronized void print(char letter){
while(index%3!=0){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(""+letter);
index++;
super.notifyAll();
}
}2.数字打印类代码
package com.bjsxt.thread;
public class NumberPrinter implements Runnable {
private Printer printer;
public NumberPrinter(Printer printer) {
this.printer=printer;
}
@Override
public void run() {
for(int i=1;i<=52;i++){
printer.print(i);
}
}
}3.字母打印类代码
package com.bjsxt.thread;
public class LetterPrinter implements Runnable{
private Printer printer;
public LetterPrinter(Printer printer){
this.printer=printer;
} @Override
public void run() {
for(char c='A';c<='z';c++){
printer.print(c);
}
}
}4.主线程测试代码
package com.bjsxt.thread;
public class Test {
public static void main(String[] args) {
//创建共享资源的对象
Printer p=new Printer();
NumberPrinter np=new NumberPrinter(p);
LetterPrinter lp=new LetterPrinter(p);
//创建代理类,并启动线程
new Thread(np).start();
new Thread(lp).start();
}
}