Skip to main content

Practical-37

Write a java program which shows the use of yield(), stop() and sleep() Methods.


Introduction

The Java thread API includes three fundamental methods: yield(), stop(), and sleep(). The yield() method is used to explicitly relinquish control of the current thread, allowing other threads of the same or higher priority to start executing. When a thread calls the stop() method, it terminates. On the other hand, the sleep() method is used to cause a thread to suspend execution for a certain amount of time, at which point the thread resumes execution as soon as possible. All three of these methods are useful in multithreaded applications.

Code

public class Test{
public static void main(String args[]) throws InterruptedException{
MyThread t1=new MyThread("Thread 1");
MyThread t2=new MyThread("Thread 2");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Both threads have finished executing.");
}
}

class MyThread extends Thread{
String name;
public MyThread(String name){
this.name=name;
}
public void run(){
for(int i=1;i<=2;i++){
System.out.println(name+" is running: "+i);
try {
Thread.sleep(100);
Thread.yield();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(name+" finished execution");
}
}

Output

Thread 1 is running: 1
Thread 2 is running: 1
Thread 1 is running: 2
Thread 2 finished execution
Thread 1 finished execution
Both threads have finished executing.
Explanation

The code creates two threads, named Thread 1 and Thread 2 and each thread has two iterations. The two threads are initialized with the MyThread class, which has the run() method implemented with a loop of 2 iterations and the certain instructions that be threads have to execute. The yield() method makes the currently executing thread to pause and allow other threads to execute. The sleep() method causes the currently executing thread to sleep and wait for a certain period of time before it can resume execution. Finally, the join() method makes sure both threads have been executed fully before the main thread continues.