我有一个线程是打印1s,2s,3s,另外一个线程是监控输入(MultipleIO),如果输入-1就暂停所有进程。我是使用了一个Boolean stop来控制线程的。可是为什么我输入-1后,打印线程里面的stop的值一直都没有变化呢?这样导致打印线程不停.难道两个线程里面的stop不指向同一个object吗?我该怎么样查看stop指向的object的地址呢
public class Core {
public static void main(String[] args) throws Exception{
Boolean stop = new Boolean(false);
Thread display = new Thread(new Display(stop));
Thread IO = new Thread(new MultipleIO(stop));
display.start();
IO.start();
}
}public class MultipleIO extends Thread{
private Boolean stop;
public MultipleIO(Boolean stop){
this.stop =stop;
}
public void run(){
Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int i;
while((i=scanner.nextInt())!=-1){
System.out.println("not -1");
}
stop=true;
}
}public class Display extends Thread{
private Boolean stop;
public Display(Boolean stop){
this.stop = stop;
}
public void run() {
try {
for(int i=1;i<Integer.MAX_VALUE&&stop==false;++i){
Thread.sleep(1000);
System.out.println(i+"s");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Core {
public static void main(String[] args) throws Exception{
Boolean stop = new Boolean(false);
Thread display = new Thread(new Display(stop));
Thread IO = new Thread(new MultipleIO(stop));
display.start();
IO.start();
}
}public class MultipleIO extends Thread{
private Boolean stop;
public MultipleIO(Boolean stop){
this.stop =stop;
}
public void run(){
Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int i;
while((i=scanner.nextInt())!=-1){
System.out.println("not -1");
}
stop=true;
}
}public class Display extends Thread{
private Boolean stop;
public Display(Boolean stop){
this.stop = stop;
}
public void run() {
try {
for(int i=1;i<Integer.MAX_VALUE&&stop==false;++i){
Thread.sleep(1000);
System.out.println(i+"s");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
解决方案 »
- java 用算法实现一个日期的前一天,不得用Calendar类。
- 如何将Sting类型的转为Timestamp类型的?
- 以前都是做BS结构,现在做非BS结构的东西,单独写一个连接数据库的类,那么JDBC的JAR包应该放在什么地方呢
- 引用Date类的问题
- Edito does not contain a main type!!!
- Java程序调用外部exe可执行程序时出现的问题
- StringTokenizer的问题,一直没有解决
- 小问题
- javaswing里取jPassword里的内容的问题。
- url.openStream()和url.openConnection().getInputStream()两者区别
- 如何获取上传到ftp服务端的文件大小
- IBM MQ问题
public class MultipleIO extends Thread{ private Boolean stop;
public MultipleIO(Boolean stop){
this.stop =stop;
}
public void run(){
Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int i;
while((i=scanner.nextInt())!=-1){
System.out.println("not -1");
}
//stop=true;
setStop(true);
}
private void setStop(boolean stop){
try{
Field f = this.stop.getClass().getDeclaredField("value");
f.setAccessible(true);
f.set(this.stop, stop);
}catch(Exception e){
e.printStackTrace();
}
}
}