How to interrupt the execution of a thread in Java

1 Answer

0 votes
class MyThread implements Runnable {
    public void run() {
        try {
            Thread.sleep(500);
            System.out.println("run()");
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
        
        System.out.println("Thread is running");
    }
}

class Program {
    public static void main(String[] args) {
        try {
            Thread trd = new Thread(new MyThread());
    
            trd.start();
    
            trd.interrupt();
    
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}



/*
run:

Exception: java.lang.InterruptedException: sleep interrupted
Thread is running

*/

 



answered Feb 2, 2024 by avibootz

Related questions

1 answer 190 views
1 answer 185 views
185 views asked Feb 2, 2024 by avibootz
1 answer 140 views
140 views asked Jan 29, 2024 by avibootz
...