Join us on Facebook

Please wait..10 Seconds Cancel

10.09.2013

// // Leave a Comment

Explain Thread In Java With Simple Java Thread Example

The Java Thread Model
The Java run-time system depends on threads for many things, and all the class libraries
are designed with multithreading in mind. In fact, Java uses threads to enable the entire
environment to be asynchronous. This helps reduce inefficiency by preventing the waste
of CPU cycles.
The value of a multithreaded environment is best understood in contrast to its counterpart.
Single-threaded systems use an approach called an event loop with polling. In this model, a
single thread of control runs in an infinite loop, polling a single event queue to decide what
to do next. Once this polling mechanism returns with, say, a signal that a network file is
ready to be read, then the event loop dispatches control to the appropriate event handler.
Until this event handler returns, nothing else can happen in the system. This wastes CPU
time. It can also result in one part of a program dominating the system and preventing any
other events from being processed. In general, in a singled-threaded environment, when a
thread blocks (that is, suspends execution) because it is waiting for some resource, the entire
program stops running.
The benefit of Java’s multithreading is that the main loop/polling mechanism is eliminated.
One thread can pause without stopping other parts of your program. For example, the idle
time created when a thread reads data from a network or waits for user input can be utilized
elsewhere. Multithreading allows animation loops to sleep for a second between each frame
without causing the whole system to pause. When a thread blocks in a Java program, only
the single thread that is blocked pauses. All other threads continue to run.
Threads exist in several states. A thread can be running. It can be ready to run as soon as
it gets CPU time. A running thread can be suspended, which temporarily suspends its activity.
A suspended thread can then be resumed, allowing it to pick up where it left off. A thread
can be blocked when waiting for a resource. At any time, a thread can be terminated, which
halts its execution immediately. Once terminated, a thread cannot be resumed.


 Test.java
class MyThread extends Thread
{
 MyThread(String s)
 {
  super(s); 
 }
 public void run()
 {
  for(int i=0;i<5;i++)
  {
   System.out.println(Thread.currentThread().getName()+" = "+i);
  }
 }
}
public class Test
{
 public static void main(String args[])
 {
  MyThread t1 = new MyThread("One"); 
  MyThread t2 = new MyThread("Two");
  MyThread t3 = new MyThread("Three");
  
 // t1.setPriority(6);
 // t3.setPriority(8);
  
  System.out.println("Thread 1.Priority = "+ t1.getPriority());
  System.out.println("Thread 2.Priority = "+ t2.getPriority());
  System.out.println("Thread 3.Priority = "+ t3.getPriority());
  
  t1.start();
  t2.run();
  t3.run();
 } 
}

0 comments:

Post a Comment