Technical Blog Of JackCHAN

August 10, 2010

Java concurrent programming (2) — Create a concurrent application in Java

Filed under: concurrent, java — Tags: , , — kaisechen @ 10:20 am

In Java, each thread is associated with a instance of Thread class.

Before JDK1.5, there is only one way to create a concurrent application. This way directly controls thread control and management, just instantiate Thread each time when the application need to initiate an asynchronous Task.

After JDK1.5, there is a new package ‘java.util.concurrent’ which provides new API supporting concurrent.  A new concept ‘executor’ can receive the application’s task and deal with it according to pre-defined rule. It separates the thread management and other rest part of the application.

The first way, when creating an instance of Thread, code running in the thread must be provided. There are two ways to do so.

1. Implement Runnable interface

Runnable interface defines run method, meant to contain the code execute in the thread.The Runnable object need be passed to a Thread constructor.

E.g.

public class Runner1 implements Runnable {

 public void run() {
 for(int i=0;i<30;i++){
 String s = Thread.currentThread().getName();
 System.out.println(s +" : "+i);
 }
 }
 
 public static void main(String args[]) {
 (new Thread(new Runner1())).start();
 }


}

2. Inherit Thread Class

The Thread Class already implements Runnable interface.  An subclass extends Thread need to override run method.

E.g.

public class MyRunner extends Thread {

 private int n;

 public MyRunner(int n) {
 this.n = n;
 }
 
 public void run(){
 for(int i=0;i<n;i++){
 System.out.println(this.getName()+":"+i);            
 }
 System.out.println(this.getName()+" Finished");
 }

 public static void main(String[] args){
 MyRunner m = new MyRunner(4);
 m.start();
 }
 

}

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.