在多线程中继承Thread类和实现runnable接口的
别并不大,但是,如果是需要继承Thread之外的其他接口,就可以使用实现runnable接口的方式。 测试类:
public class PrintString {
private boolean isContinuePrint = true;
public boolean isContinuePrint() {
return isContinuePrint;
}
public void setContinuePrint(boolean isContinuePrint) {
this.isContinuePrint = isContinuePrint;
}
public void printStringMethod() {
try {
while (isContinuePrint == true) {
System.out.println("run printStringMethod threadName="
+ Thread.currentThread().getName());
Thread.sleep(1000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行类testRun:
public class Run {
public static void main(String[] args) {
PrintString printStringService = new PrintString();
printStringService.printStringMethod();
System.out.println("我要停止它!stopThread="
+ Thread.currentThread().getName());
printStringService.setContinuePrint(false);
}
}
发现是停不下来的
标签:printStringService,isContinuePrint,Thread,关键字,boolean,volatile,线程,public,printSt From: https://blog.51cto.com/u_15927490/7465553