Switch to full style
Java2 codes,problems ,discussions and solutions are here
Post a reply

What is Multithreading?

Wed Jul 04, 2007 12:15 am

What is Multithreading? How to add threading to my application in java?
-----------------------------------------


A thread executes a series of instructions. Every line of code that is executed is done so by a thread. Some threads can run for the entire life of the applet, while others are alive for only a few milliseconds.

Multithreading is the ability to have various parts of program perform program steps seemingly at the same time. Java let programs interleave multiple program steps through the use of threads. For example,one thread controls an animation, while another does a computation. In Java, multithreading is not only powerful, it is also easy to implement.

You can implement threads within a java program in two ways :
  • Creating an object that extends Class Thread.
  • Implementing the interface Runnable.
The key difference between the two is that Thread class has a strart() method which your program simple calls whereas the Runnable class does not have a start method and you must create a Thread object and pass your thread to its constructor method. You never call run() method directly; the start method calls it for you.

Thread Example:

java code
Class MyProcess extends Thread{
Public void run(){
}
public static void main(String args[]){
MyProcess mp = new MyProcess();
mp.start();
}
}
Class MyProcess implements Runnable {
Public void run(){
}
public static void main(String args[]){
Thread mp = new Thread(new MyProcess());
mp.start();
}
}
]


So you put your code that you want to run inside the run() function , another important information about threads that each thread can have different status such as :
  • Waiting: waiting other threads.
  • Running: executing thread.
  • New : not yet started.
  • Terminated: a thread finished running run() function.
  • Blocked: a thread waiting for IO.
  • Timed_Waiting: Waiting for a specific time by code (ex Thread.sleep function).

You can get the current thread status using for example :
java code
static void showThreadStatus(Thread mythread) {
System.out.println(mythread.getName()+" Alive:"
+mythread.isAlive()+" State:" +mythread.getState() );
}




Post a reply
  Related Posts  to : What is Multithreading?
 C++ Multithreading     -  
 Java - Multithreading     -  

Topic Tags

Java Threads