How to do it...

Follow these steps to implement the example:

  1. Create a class called DataSourcesLoader and specify that it implements the Runnable interface:
        public class DataSourcesLoader implements Runnable {
  1. Implement the run() method. It writes a message to indicate that it starts its execution, sleeps for 4 seconds, and writes another message to indicate that it ends its execution:
        @Override 
public void run() {
System.out.printf("Beginning data sources loading: %s ",
new Date());
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
          System.out.printf("Data sources loading has finished: %s
",
new Date());
}
  1. Create a class called NetworkConnectionsLoader and specify that it implements the Runnable interface. Implement the run() method. It will be equal to the run() method of the DataSourcesLoader class, but it will sleep for 6 seconds.
  2. Now, create a class called Main that contains the main() method:
        public class Main { 
public static void main(String[] args) {
  1. Create an object of the DataSourcesLoader class and a thread to run it:
       DataSourcesLoader dsLoader = new DataSourcesLoader(); 
Thread thread1 = new Thread(dsLoader,"DataSourceThread");
  1. Create an object of the NetworkConnectionsLoader class and a thread to run it:
        NetworkConnectionsLoader ncLoader = new NetworkConnectionsLoader(); 
Thread thread2 = new Thread(ncLoader,"NetworkConnectionLoader");
  1. Call the start() method of both the thread objects:
        thread1.start(); 
thread2.start();
  1. Wait for the finalization of both the threads using the join() method. This method can throw an InterruptedException exception, so we have to include the code to catch it:
       try { 
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
  1. Write a message to indicate the end of the program:
        System.out.printf("Main: Configuration has been loaded: %s
",
new Date());
  1. Run the program and see the results.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.69.110