в моей основной программе Java не прерывается. Зачем?Основная тема, кажется, не прерывается
/*
* This class counts till infinity
*/
class infinityT extends Thread{
int counter = 0;
public void run(){
try{
while(true){
if(counter>500){
// this class will throw compilation error here as Thread.sleep is not a valid method here as it does not extend Thread class
Thread.sleep(1000);
}
System.out.println(counter++);
}
}catch(InterruptedException e){
System.out.println("infinity Interrupted: "+counter);
}
}
}
class interruption{
public static void main(String args[]){
Thread t = new Thread(new infinityT());
// start the thread
t.start();
try{
// main thread does not seem to interrupt
Thread.currentThread().interrupt();
Thread.sleep(2000);
}catch(InterruptedException e){
System.out.println("Main thread interrupted!");
}
t.interrupt();
}
}
Выход:
...
...
499
500
infinity Interrupted: 501
Что вы пытаетесь достичь здесь? Код не имеет для меня никакого смысла. – Fildor
вы никогда не знаете порядок, в котором запланированы потоки. Поэтому, когда вы начали поток t, основной поток, возможно, был помещен в фоновый режим, поэтому вы никогда не видели прерывания основного потока. Попробуйте запустить программу несколько раз, чтобы увидеть различия. – MohamedSanaulla
@Fildor: это просто демо-программа и считается до бесконечности, если не прерывается –