How to create thread


Thread is the feature of mostly languages including Java. Threads allow the program to perform multiple tasks simultaneously. Process speed can be increased by using threads because the thread can stop or suspend a specific running process and start or resume the suspended processes. Multitasking or multiprogramming is delivered through the running of multiple threads concurrently. If your computer does not have multi-processors then the multi-threads really do not run concurrently.


// Create a new thread.

class NewThread implements Runnable {

   Thread t;

   NewThread(String name,int priority) {

      // Create a new, second thread

      t = new Thread(this,name);

    t.setPriority(priority);

      System.out.println("Child thread: " + t);

      t.start(); // Start the thread

   }

 

   // This is the entry point for the second thread.

   public void run() {

      try {

         for(int i = 5; i > 0; i--) {

            System.out.println(t+":"+ i);

            // Let the thread sleep for a while.

            Thread.sleep(500);

         }

     } catch (InterruptedException e) {

         System.out.println("Child interrupted.");

     }

     System.out.println("Exiting child thread.");

   }

}

class ThreadDemo {

   public static void main(String args[]) {

 NewThread mythread1=new NewThread("Child Thread 1",6); // create a new thread

    NewThread mythread2=new NewThread("Child Thread 2",9);

      try {

         for(int i = 5; i > 0; i--) {

           System.out.println("Main Thread: " + i);

           Thread.sleep(1000);

         }

      } catch (InterruptedException e) {

         System.out.println("Main thread interrupted.");

      }

      System.out.println("Main thread exiting.");

   }

}

Output:

 

Post a Comment

Copyright © Rough Record. Designed by OddThemes