package thread;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
/*
* 线程的中断
* 以往有时候会使用stop()停止线程,但当前版本的JDK早已废除stop().
* 现在提倡在run()方法中使用无线循环的形式,然后使用一个布尔型标记控制
* 循环的停止。
*/
public class InterruptedSwing extends JFrame{
Thread thread ;
public InterruptedSwing() {
super();
//创建进度条
final JProgressBar pb=new JProgressBar();
//将进度条放置在窗体合适位置。
getContentPane().add(pb,BorderLayout.NORTH);
thread =new Thread(new Runnable() {
int count=0;
@Override
public void run() {
while(true) {
pb.setValue(++count);//设置进度条当前值
try {
thread.sleep(1000);//使线程休眠1000毫秒
} catch (InterruptedException e) {
System.out.println("当前线程被中断");
break;
}
}
}
});
thread.start();//启动线程
thread.interrupt();//中断线程
}
public static void init(JFrame frame,int width,int height) {
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
public static void main(String[] args) {
init(new InterruptedSwing(),100,100);
}
}
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
/*
* 线程的中断
* 以往有时候会使用stop()停止线程,但当前版本的JDK早已废除stop().
* 现在提倡在run()方法中使用无线循环的形式,然后使用一个布尔型标记控制
* 循环的停止。
*/
public class InterruptedSwing extends JFrame{
Thread thread ;
public InterruptedSwing() {
super();
//创建进度条
final JProgressBar pb=new JProgressBar();
//将进度条放置在窗体合适位置。
getContentPane().add(pb,BorderLayout.NORTH);
thread =new Thread(new Runnable() {
int count=0;
@Override
public void run() {
while(true) {
pb.setValue(++count);//设置进度条当前值
try {
thread.sleep(1000);//使线程休眠1000毫秒
} catch (InterruptedException e) {
System.out.println("当前线程被中断");
break;
}
}
}
});
thread.start();//启动线程
thread.interrupt();//中断线程
}
public static void init(JFrame frame,int width,int height) {
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
public static void main(String[] args) {
init(new InterruptedSwing(),100,100);
}
}