Points To Remember
- We can make threads in java by implementing Runnable Interface. Any class that implements this interface must override its run() method.
- The call to start() method internally calls the run() method of the thread.
- We can not guarantee which thread would be executed first. Thread Priority only promises the cpu time and not that it will be run first.
Program : How to make threads by implementing Runnable Interface
In the below example we are implementing the Runnable interface and creating two threads "t1" and "t2" and calling the run() method using thread.start(). We run the same program twice and we might get different outputs each time as shown below.class Test implements Runnable{Running for first time
String msg;
public void run(){
System.out.println("Running Thread" + msg);
}
public Test(String msg){
this.msg = msg;
}
public static void main(String args[]){
System.out.println("Stating main");
Thread t1 = new Thread(new Test("t1"));
Thread t2 = new Thread(new Test("t2"));
t1.start();
t2.start();
System.out.println("Ending main");
}
}
Stating mainRunning for second time
Ending main
Running Threadt2
Running Threadt1
Stating mainThe abobe proves that we can not judge that which thread will be executed first.
Ending main
Running Threadt2
Running Threadt1
Program : How to make threads using Runnable Interface in a different class.
The below program shows how we can threads of a class that implements Runnable Interface and call these threads from a different class. Here we make a class Sample that implements Runnable Interface and a Test class that makes threads of this class.class Sample implements Runnable{
String msg;
public void run(){
System.out.println("Running Thread" + msg);
}
public Sample(String msg){
this.msg = msg;
}
}
class Test{
public static void main(String args[]){
System.out.println("Stating main");
Thread t1 = new Thread(new Sample("t1"));
Thread t2 = new Thread(new Sample("t2"));
t1.start();
t2.start();
System.out.println("Ending main");
}
}
Stating mainRunning the program for the second time
Ending main
Running Threadt1
Running Threadt2
Stating main
Running Threadt1
Ending main
Running Threadt2
Comments
Post a Comment