Thread Class Methods Programs
Thread Class Methods Programs
The suspend() method of thread class puts the thread from running to
waiting state. This method is used if you want to stop the thread execution
and start it again when a certain event occurs. This method allows a thread
to temporarily cease execution. The suspended thread can be resumed using
the resume() method.
Syntax:-public final void suspend()
resume() method
The resume() method of thread class is only used with suspend() method.
This method is used to resume a thread which was suspended using
suspend() method. This method allows the suspended thread to start again.
Syntax:-public final void resume()
//Example on suspend() and resume() methods
class Thread1 extends Thread{
String name=getName();
System.out.println(name+"begins its execution");
for (int i=1;i<=20;i++){
System.out.println(name+":"+i);
if(name.equals("Thread-1")){
System.out.println(name+"is stopped its execution-Dead State");
stop();
}
}
System.out.println(name+"Ends:");
}
public static void main(String[] args) {
}
}
Yield() method :-
A yield() method is a static method of Thread class and it can stop the
currently executing thread and will give a chance to other waiting threads
of the same priority. If in case there are no waiting threads or if all the
waiting threads have low priority then the same thread will continue its
execution.
}
}
class Thr1 extends Thread
{
public void run()
{
System.out.println("Child Thread begins:");
for(int i=1;i<=20;i++)
System.out.println("Child Thread:"+i);
System.out.println("Child Thread Ends:");
}
public static void main(String[] args)
{
Thr1 t1=new Thr1();
t1.setPriority(10);
t1.start();
System.out.println("Main Thread begins:");
for(int i=1;i<=20;i++)
System.out.println("Main:"+i);
System.out.println("Main1 Thread Ends:");
}
}
//Example on Inter-Thread Communication.
class Customer
{
double balance=10000;
public synchronized void withdraw(double amount)
{
balance-=amount;
System.out.println("WITHDRAW MONEY SUCCESSFULLY:");
}
public synchronized void deposit(double amount){
}
}
class Thread1 extends Thread
{
Customer c;
public Thread1(Customer c){this.c=c;}
public void run()
{
c.withdraw(12000);
}
}
class Thread2 extends Thread
{
Customer c;
public Thread2(Customer c){this.c=c;}