how to use threads in java create start pause interrupt and join
In Java, you can use threads to execute multiple tasks concurrently. Here are the basic steps to create, start, pause, interrupt, and join threads in Java:
- Create a thread by extending the
Thread
class or implementing theRunnable
interface.
public class MyThread extends Thread { public void run() { // code to be executed in the thread } }
- Start the thread using the
start()
method.
MyThread thread = new MyThread(); thread.start();
- Pause the thread using the
sleep()
method.
try { Thread.sleep(1000); // pause for 1 second } catch (InterruptedException e) { // handle the exception }
- Interrupt the thread using the
interrupt()
method.
thread.interrupt();
- Join the thread using the
join()
method.
try { thread.join(); // wait for the thread to finish } catch (InterruptedException e) { // handle the exception }
Here's an example that demonstrates how to use threads in Java:
public class ThreadExample implements Runnable { public void run() { try { for (int i = 1; i <= 5; i++) { System.out.println("Thread " + Thread.currentThread().getId() + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Thread " + Thread.currentThread().getId() + " interrupted."); } } public static void main(String[] args) { Thread t1 = new Thread(new ThreadExample()); Thread t2 = new Thread(new ThreadExample()); t1.start(); t2.start(); try { Thread.sleep(5000); t1.interrupt(); t2.interrupt(); t1.join(); t2.join(); } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } }
In this example, we create a class ThreadExample
that implements the Runnable
interface. The run()
method of this class simply prints some messages to the console and sleeps for one second between each message. In the main()
method, we create two threads t1
and t2
using ThreadExample
as the target. We start both threads, then pause the main thread for five seconds. After five seconds, we interrupt both threads, wait for them to finish using join()
, and print a message to the console indicating that the main thread is exiting.
Note that when a thread is interrupted, the InterruptedException
is thrown, which can be caught and handled by the thread. The join()
method is used to wait for a thread to finish before continuing with the rest of the program.