62,614
社区成员
发帖
与我相关
我的任务
分享
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
public class Communicate extends JFrame {
Thread t1;
Thread t2;
private int count = 0;
final JProgressBar progressBar = new JProgressBar();
public static void main(String[] args) throws InterruptedException {
init(new Communicate(), 150, 100);
}
public Communicate() throws InterruptedException {
super();
progressBar.setStringPainted(true);
getContentPane().add(progressBar, BorderLayout.NORTH);
deValue();
addValue();
t1.start();
synchronized (t1) {
Thread.currentThread().sleep(1000);
t1.wait();
}
t2.start();
}
public void addValue() {
t1 = new Thread(new Runnable() {
public void run() {
try {
System.out.println("线程退出");
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void deValue() {
t2 = new Thread(new Runnable() {
public void run() {
while (true) {
if (count == 0) {
synchronized (t1) {
try {
System.out.println("t2等待");
t1.wait(); //这里应该等待,为什么t1结束后就被唤醒了?
System.out.println("t2等待结束");
count = 10;
}
catch (Exception e) {
e.printStackTrace();
}
}
}
progressBar.setValue(--count);
System.out.println("进度条的当前值为:" + count);
}
}
});
}
public static void init(JFrame frame, int width, int height) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
}
输出的是:
线程退出
t2等待
请问为什么?
解释稍后回复。这是一个很好的面试题哦