Run program in background

There may be situation where you may want to run your application in background. For example, assume there are four logic/processes in your application and you want three processes to run in background. In this case these three processes running in background would reduce user waiting time.

Program Explanation:
There are 2 classes in this example.
 1) MainClass.java
 2) MyThread.java
 MainClass class calls MyThread class by passing parameter to MyThread class.
 The code which is to be executed in background is placed in MyThread class.


MainClass.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.utility;

/*
 This class demonstrates how to run program in background. 
 This class calls MyThread class by passing parameter to MyThread class.
 The code which is to be executed in background is placed in MyThread class.
 
 */
public class MainClass {

 public static void main(String[] args) {
  
     new MyThread("world!").start(); //passing parameter(this runs in background)
     
     System.out.println("After Asynchronous Call"); 
  
  //for testing
  /*for(int i=0;i<1000;i++)
  {
   System.out.println("After Asynchronous Call"); 
  }*/
 }
}



MyThread.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package com.utility;
/*
This class runs in background.
 */
class MyThread extends Thread {
 
 private String to;

 //This constructor accepts parameter sent from Main class
    public MyThread(String to) 
    {
        this.to = to;
    }

    @Override
    public void run() {
        System.out.println("hello " + to);        
    }
}



Output:


Output if for loop is uncommented in MainClass.java (this o/p may vary)


No comments:

Post a Comment