是传参的问题吗
String类型作为参数传递,是引用传递,也就是传递的是地址,你在外面修改了String的指向,不会影响方法内的String,因为他们之间只是开始指向的地址一样,后面外面的String指向的地址变了,而里面的没有变。
直接看代码,你输入的exit信息与打印下载中...不是同一个线程
ThreadStop.java中
command = in.readLine();
改成
RunnerStop._command = in.readLine();
RunnerStop.java中
public static String _command;
改成
public static volatile String _command;
String类型不能实现线程之间共享数据。把command的类型改成AtomicReference。
因为你开始command=" ",线程已经启动,你输入exit后又启动了新的线程起始的线程并未关闭
使用同一个command,然后加上 volatile 试一下
可以使用StringBuffer,这是线程安全的,如下:
public class TestThread {
public static void main(String[] args){
StringBuffer cc= new StringBuffer("");
Thread th = new Thread(new MyThread(cc));
th.start();
for(int i = 0; i < 99999; i++){
System.out.println(i);
};
cc.append("exit");
}
public static class MyThread implements Runnable{
private StringBuffer comm;
public MyThread(StringBuffer comm){
this.comm = comm;
}
@Override
public void run() {
while(!comm.toString().equalsIgnoreCase("exit")){
System.out.println("开始。。。。。");
try {
Thread.sleep(10000);
}catch (Exception ex){
}
System.out.println("结束。。。。。");
}
}
}
}