How to pause a thread in Java

2 Answers

0 votes
import static java.lang.Thread.currentThread;
import java.util.concurrent.TimeUnit;
 
class Play implements Runnable {
    private volatile boolean stop = false;
     
    public void run() {
         
        while(!stop) {
            System.out.println("Play thread running.....");            
 
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {               
                e.printStackTrace();
            }
             
            System.out.println("Play thread resumed.....");
        }
         
        System.out.println("Play thread stopped");
    }
     
    public void stop() {
        stop = true;
    }
}
 
public class MyClass {
    public static void main(String args[]) throws InterruptedException {
        Play game = new Play();
 
        Thread tr1 = new Thread(game, "TR1");
        tr1.start();
         
        System.out.println(currentThread().getName() + " stop the thread");
        game.stop();
         
        TimeUnit.MILLISECONDS.sleep(300);
         
        System.out.println(currentThread().getName() + " end");
    }
}
  
  
  
  
/*
run:
  
Play thread running.....
main stop the thread
Play thread resumed.....
Play thread stopped
main end
  
*/

 



answered Nov 9, 2021 by avibootz
edited Nov 9, 2021 by avibootz
0 votes
import static java.lang.Thread.currentThread;
import java.util.concurrent.TimeUnit;
 
class Play implements Runnable {
    private volatile boolean stop = false;
     
    public void run() {
         
        while(!stop) {
            System.out.println("Play thread running.....");            
 
            try {
                Thread.sleep(444);
            } catch (InterruptedException e) {               
                e.printStackTrace();
            }
             
            System.out.println("Play thread resumed.....");
        }
         
        System.out.println("Play thread stopped");
    }
     
    public void stop() {
        stop = true;
    }
}
 
public class MyClass {
    public static void main(String args[]) throws InterruptedException {
        Play game = new Play();
 
        Thread tr1 = new Thread(game, "TR1");
        tr1.start();
         
        System.out.println(currentThread().getName() + " stop the thread");
        game.stop();
         
        TimeUnit.MILLISECONDS.sleep(222);
         
        System.out.println(currentThread().getName() + " end");
    }
}
  
  
  
  
/*
run:
  
Play thread running.....
main stop the thread
main end
Play thread resumed.....
Play thread stopped
  
*/

 



answered Nov 9, 2021 by avibootz

Related questions

1 answer 207 views
1 answer 128 views
1 answer 189 views
1 answer 209 views
1 answer 184 views
184 views asked Feb 2, 2024 by avibootz
...