Showing posts with label Threads. Show all posts
Showing posts with label Threads. Show all posts

Points To Remember


  • TimerTask is a class that can run a Thread repeatedly after a specific period.
  • You can either implement your own class also by implementing Runnable Interface.
    • Then you may need to put your thread to sleep and then resume the thread after a desired interval.
The TimerTask will do this more efficiently for you then implementing your own code.

How to schedule a Thread to run after fixed interval

We will be using TimerTask to schedule the Thread after every 1 sec.

TimerTask class in Java implements Runnable interface and has the following methods.

  • cancel - to cancel the timer task when needed.
  • scheduledExecutionTime - gives the time when the task was last executed successfully.
  • run - an abstract method that needs to be implemented.

MyTask.java

import java.util.TimerTask;
import java.util.Date;

class MyTask extends TimerTask {

static int count = 0;

@Override
public void run(){
if(count < 5){
System.out.println(" MyTask called ### count = "+ (++count));
}
else {
cancel();
System.out.println("######### TASK CANCELLED #######");
}
}

}


TestTimerTask.java

import java.util.TimerTask;
import java.util.Timer;

class TestTimerTask {

public static void main(String args[]){

TimerTask task = new MyTask();
Timer timer = new Timer();
timer.scheduleAtFixedRate(task,0,1000);

}

}

 MyTask called  ### count = 1
 MyTask called  ### count = 2
 MyTask called  ### count = 3
 MyTask called  ### count = 4
 MyTask called  ### count = 5
#########    TASK CANCELLED    #######

So Thread goes on executing till it is stopped manually or till cancel() is called on the task.

Points To Remember
  • We can implement Runnable interface or extend Thread class to create threads.
  • We have to override the run() method to define the functionality of thread.
  • We should call start() method to start execution of a thread as a new entity, if we call run() method on a thread then it will not start a new thread.
  • We cannot guarantee which thread will execute first even if we prioritize the threads.
  • A thread whose run() method is executed completely reaches the dead state and cannot be invoked again.
Program : Making 3 Threads using Thread Class
In the following example we are making three different threads in the class Test which extends the Thread class. We just pass a parameter name to each object of Test thread to distinguish between them.
class Test extends Thread{

String name;

public Test(String name){
this.name = name;
}

public static void main(String args[]){
System.out.println("main started");

Thread t1 = new Thread(new Test("Thread t1"));
Thread t2 = new Thread(new Test("Thread t2"));
Thread t3 = new Thread(new Test("Thread t3"));
t1.start();
t2.start();
t3.start();

System.out.println("main ended");

}

@Override
public void run(){
System.out.println(name);
}

}
Running the program for the first time.
main started
Thread t1
Thread t3
Thread t2
main ended
Running the program for the second time.
main started
main ended
Thread t2
Thread t1
Thread t3
Running the program for the third time.
main started
main ended
Thread t1
Thread t3
Thread t2
The above outputs confirms that we cannot guarantee the execution of any thread. Any thread may execute first.
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{
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");
}

}
Running for first time
Stating main
Ending main
Running Threadt2
Running Threadt1
Running for second time
Stating main
Ending main
Running Threadt2
Running Threadt1
The abobe proves that we can not judge that which thread will be executed first.
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 main
Ending main
Running Threadt1
Running Threadt2
Running the program for the second time
Stating main
Running Threadt1
Ending main
Running Threadt2