Thursday, February 6, 2014

Java - Thread (while and interrupt)

class InfinitThread extends Thread {
int value = Integer.MIN_VALUE;
private boolean flag = true;

public void run() {
while (flag) {
value++;

if (value == Integer.MAX_VALUE) {
value = Integer.MIN_VALUE;

System.out.println("MAX_VALUE");
}
}
}

public void setFlag(boolean flag) {
this.flag = flag;
}
}

public class Test {

public static void main(String[] args) throws InterruptedException {
InfinitThread infinitThread = new InfinitThread();

infinitThread.start();
Thread.sleep(2000);

System.out
.format("isInterrupted = %s\n", infinitThread.isInterrupted());

infinitThread.interrupt();

System.out
.format("isInterrupted = %s\n", infinitThread.isInterrupted());

infinitThread.setFlag(false); // delete this line and try
}
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.