J
Jack Dowson
Hello Everybody:
Here is a demo to test java's multithread:
class MyThread extends Thread{
public void run(){
while(true){
System.out.println(getName() + " is running!");
try{
sleep(1000);
}catch(InterruptedException e){
System.out.println(e.getMessage());
}
}
}
}
class InterruptThreadDemo{
public static void main(String[] args) throws InterruptedException{
MyThread m = new MyThread();
System.out.println("Starting thread...");
m.start();
Thread.sleep(2000);
System.out.println("Interrupt thread...");
m.interrupt();
Thread.sleep(2000);
System.out.println("Stopping application...");
}
}
The result is:
Starting thread...
Thread-0 is running!
Thread-0 is running!
Interrupt thread...
Thread-0 is running!
sleep interrupted
Thread-0 is running!
Thread-0 is running!
Stopping application...
Thread-0 is running!
Thread-0 is running!
Thread-0 is running!
Thread-0 is running!
Thread-0 is running!
.......
The outcome is bit out of my anticipation:
What happened to create the sentence "sleep interrupted!"
Any help will be greatly appreciated!
Here is a demo to test java's multithread:
class MyThread extends Thread{
public void run(){
while(true){
System.out.println(getName() + " is running!");
try{
sleep(1000);
}catch(InterruptedException e){
System.out.println(e.getMessage());
}
}
}
}
class InterruptThreadDemo{
public static void main(String[] args) throws InterruptedException{
MyThread m = new MyThread();
System.out.println("Starting thread...");
m.start();
Thread.sleep(2000);
System.out.println("Interrupt thread...");
m.interrupt();
Thread.sleep(2000);
System.out.println("Stopping application...");
}
}
The result is:
Starting thread...
Thread-0 is running!
Thread-0 is running!
Interrupt thread...
Thread-0 is running!
sleep interrupted
Thread-0 is running!
Thread-0 is running!
Stopping application...
Thread-0 is running!
Thread-0 is running!
Thread-0 is running!
Thread-0 is running!
Thread-0 is running!
.......
The outcome is bit out of my anticipation:
What happened to create the sentence "sleep interrupted!"
Any help will be greatly appreciated!