Creating Multiple Threads in java

Objects provide a way to divide a program into independent sections. Often, you also need to turn a program into separate, independently running sub tasks.

Each of these independent sub tasks is called a thread, and you program as if each thread runs by itself and has the CPU to itself. Some underlying mechanism is actually dividing up the CPU time for you, but in general, you don’t have to think about it, which makes programming with multiple threads a much easier task.

A process is a self-contained running program with its own address space. A multitasking operating system is capable of running more than one process (program) at a time, while making it look like each one is chugging along on its own, by periodically providing CPU cycles to each process. A thread is a single sequential flow of control within a process. A single process can thus have multiple concurrently executing threads.

There are many possible uses for multithreading, but in general, you’ll have some part of your program tied to a particular event or resource, and you don’t want to hang up the rest of your program because of that. So you create a thread associated with that event or resource and let it run independently of the main program. A good example is a “quit” button—you don’t want to be forced to poll the quit button in every piece of code you write in your program and yet you want the quit button to be responsive, as if you were checking it regularly. In fact, one of the most immediately compelling reasons for multithreading is to produce a responsive user interface.

Program MultThreadDemo.java

class NewThread implements Runnable
{
 String name;
 Thread t;
 NewThread(String Threadname)
  {
   name=Threadname;
   t=new Thread(this,name);
   System.out.println("New thread :"+t);
   t.start();
  }
 public void run()
 {
  try
  {
   for(int i=5;i>0;i--)
   {
   System.out.println(name+":"+i);
   Thread.sleep(1000);
   }
  }

 catch(InterruptedException e)
  {
   System.out.println(name+"Interrupted");
  }
 System.out.println(name+"existing");
 }
}
class MultThreadDemo
  {
   public static void main(String arg[])
     {
      new NewThread("One");
      new NewThread("Two");
      new NewThread("Three");
      try
       {
        Thread.sleep(1000);
       }
      catch(InterruptedException e)
       {
        System.out.println("Main Thread Interrupted");
       }
      System.out.println("Main Thread Existing");
     }
  }
Output 


G:\>javac MultThreadDemo.java

G:\>java MultThreadDemo
New thread :Thread[One,5,main]
New thread :Thread[Two,5,main]
One:5
New thread :Thread[Three,5,main]
Two:5
Three:5
One:4
Main Thread Existing
Two:4
Three:4
One:3
Two:3
Three:3
One:2
Two:2
Three:2
One:1
Two:1
Three:1
Oneexisting
Twoexisting
Threeexisting


Creating Multiple Threads in java

0 comments:

Post a Comment

 

learn java programming Copyright © 2011-2012 | Powered by appsackel.org