2015년 11월 2일 월요일

[OO-Java] Sample Code !! - Thread Kill


public class ThreadKill {

public static void main(String[] args) {

// Create tasks
Runnable MyTaskB = new Task2();

// Create threads
Thread thread0 = new Thread(MyTaskB);
thread0.start();
}
}

//The task for printing a character a specified number of times
class Task1 implements Runnable {
int i = 0;
int j = 0;

public void run() {

Thread t = Thread.currentThread();
String name = t.getName();

try {
while (!Thread.interrupted()) {
i += 1;
j += 1;
System.out.println("[" + name + "] " + "i: " + i + " j: " + j);
Thread.sleep(1000);
}
} catch(InterruptedException ex) {
// The interrupt() method interrupts a thread in the following way:
// If a thread is currently in the Ready or Running state,
//    its interrupted flag is set;
// if a thread is currently blocked,
//      it is awakened and enters the Ready state,
//      and a java.lang.InterruptedException is thrown.
// ex.printStackTrace(); //Verify What happens if we take out this statement

}
}
}

//The task class for printing numbers from 1 to n for a given n
class Task2 implements Runnable {

@Override /** Tell the tread how to run */
public void run() {

Thread thread1 = new Thread(new Task1());
Thread thread2 = new Thread(new Task1());
Thread thread3 = new Thread(new Task1());

thread1.start();
thread2.start();
thread3.start();

try {
Thread.sleep(2000);
}  catch(InterruptedException ex) {
// ex.printStackTrace(); //Verify What happens if we take out this statement
}

thread1.interrupt();
thread2.interrupt();
thread3.interrupt();

//thread1.stop(); // Try this One!!
//thread2.stop();
//thread3.stop();

System.out.print("Num: " + 1 + " ");
}
}