62,614
社区成员
发帖
与我相关
我的任务
分享
MyThread r2 = new MyThread(sd1);
if ( btnSd.getText().equals("启动")) {
r2.bStop = true;
r2.start();
btnSd.setText("停止");
}
else {
r2.bStop = false;
r2.interrupt();
btnSd.setText("启动");
}
public class MyThread extends Thread {
private JSlider iSd; //进度条控件,JSlider
public boolean bStop; //是否要终止线程
//类的构造函数
public MyThread(JSlider sd) {
iSd = sd;
nType = 2;
}
//重写run方法
@Override
public void run() {
for(int i=0;i<10;i++) {
if( !bStop) {
break; //用户终止线程
}
iSd.setValue(0);
int nPos;
while(iSd.getValue()<iSd.getMaximum()){
System.out.println(bStop);
if ( !bStop) {
break; //用户终止线程
}
nPos = iSd.getValue();
nPos++;
iSd.setValue(nPos);
try {
this.sleep(10);
}
catch(InterruptedException e) {
System.out.println("err");
}
}
}
}
}
JButton btnSd = new JButton("\u542F\u52A8");
btnSd.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
MyThread r2 = new MyThread(sd1);
if ( btnSd.getText().equals("启动")) {
r2.bStop = true;
r2.start();
btnSd.setText("停止");
}
else {
r2.bStop = false;
r2.interrupt();
btnSd.setText("启动");
}
}
});
这是线程类的代码,继承Thread,是一个新建的文件
package aa;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.JTextField;
/**
* @author 作者 E-mail:
* @version 创建时间:Dec 5, 2017 10:25:56 AM
* 类说明
*/
public class MyThread extends Thread {
private JSlider iSd; //进度条控件,JSlider
public volatile boolean bStop; //是否要终止线程
//类的构造函数
public MyThread(JSlider sd) {
iSd = sd;
}
//重写run方法
@Override
public void run() {
//线程的控件类型为JSlider(进度条)
//不停的循环
//bStop = true; //默认是进行线程
for(int i=0;i<3;i++) {
if( !bStop) {
break; //用户终止线程
}
iSd.setValue(0);
int nPos;
while(iSd.getValue()<iSd.getMaximum()){
System.out.println(bStop);
if ( !bStop) {
break; //用户终止线程
}
nPos = iSd.getValue();
nPos++;
iSd.setValue(nPos);
try {
this.sleep(10);
}
catch(InterruptedException e) {
System.out.println("err");
}
}
}
}
}
MyThread r2 = new MyThread(sd1);
if ( btnSd.getText().equals("启动")) {
r2.bStop = true;
r2.start();
btnSd.setText("停止");
}
else {
r2.bStop = false;
r2.interrupt();
btnSd.setText("启动");
}
r2.bStop = false; 为什么不起作用?
public class MyThread extends Thread {
private JSlider iSd; //进度条控件,JSlider
public volatile boolean bStop; //是否要终止线程
//类的构造函数
public MyThread(JSlider sd) {
iSd = sd;
}
//重写run方法
@Override
public void run() {
//线程的控件类型为JSlider(进度条)
//不停的循环
//bStop = true; //默认是进行线程
for(int i=0;i<10;i++) {
if( !bStop) {
break; //用户终止线程
}
iSd.setValue(0);
int nPos;
while(iSd.getValue()<iSd.getMaximum()){
System.out.println(bStop);
if ( !bStop) {
break; //用户终止线程
}
nPos = iSd.getValue();
nPos++;
iSd.setValue(nPos);
try {
this.sleep(10);
}
catch(InterruptedException e) {
System.out.println("err");
}
}
}
}
}