Threads Methods in Java with Example

In this page you will get threads methods in Java with example source code. You can find infomration about Java Threads methods with example program.

In this page you will get threads methods in Java with example source code. You can find infomration about Java Threads methods with example program.

class Methods implements Runnable{
Thread t;
String name;
public Methods(String n){
name = n;
System.out.println(name +” Thread started”);
t = new Thread(this);
t.start();
}
public void run(){
try {
for (int i = 0; i < 50; i++){
System.out.print(i+”  ”);
Thread.sleep(1000);
}
} catch (InterruptedException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name +” Thread Exited”);
}
}

public class ThreadMethods {
public static void main(String args[]) {
System.out.println(“Main Thread started” );
Methods obj1 =  new Methods (“one”);
Methods obj2 = new Methods (“Two”);
System.out.println(“Thread one is alive: ” + obj1.t.isAlive());
System.out.println(“Thread Two is alive: ” + obj2.t.isAlive());
try {
Thread.sleep(1000);
System.out.println(“Suspending thread one”);
obj1.t.suspend();
Thread.sleep(1000);
System.out.println(“resuming thread one”);
obj1.t.resume();
Thread.sleep(1000);
System.out.println(“Suspending thread two”);
obj2.t.suspend();
Thread.sleep(1000);
System.out.println(“resuming thread two”);
obj2.t.resume();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
obj1.t.join();
obj2.t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(“Thread one is alive: ” + obj1.t.isAlive());
System.out.println(“Thread Two is alive: ” + obj2.t.isAlive());
System.out.println(“Main Thread Exited”);
}
}

Result:
Main Thread started
one Thread started
Two Thread started
Thread one is alive: true
Thread Two is alive: true
0  0  1  1  Suspending thread one
2  resuming thread one
2  3  3  Suspending thread two
4  resuming thread two
4  5  5  6  6  7  7  8  8  9  9  10  10  11  11  12  12  13  13  14  14  15  15  16  16  17  17  18  18  19  19  20  20  21  21  22  22  23  23  24  24  25  25  26  26  27  27  28  28  29  29  30  30  31  31  32  32  33  33