Showing posts with label Java Thread. Show all posts
Showing posts with label Java Thread. Show all posts

Saturday, February 5, 2011

Java Tutorial: Thread Example

Two ways of Creating Thread

1. Extending from Thread class
  • Extends a class from the Thread class
  • Override the run( )
  • Create an instance of the above class
  • Start the Thread

/**
*
* @author paiman
*/
class DispThread extends Thread{

String msg;

public DispThread(String msg) {
this.msg = msg;
}

@Override
public void run(){
for(int i=0; i<5;i++){
System.out.println(msg);
}

}
}


/**
*
* @author paiman
*/
public class ThreadTest {

public static void main (String[]args){
DispThread dt1 = new DispThread("Thread");
DispThread dt2 = new DispThread("Example");
dt1.start();
dt2.start();
}
}

2. Implementing Runnable
  • Implement Runnable on a class
  • Implement the run( ) of the Runnable interface
  • Create an instance of the above class
  • Create a Thread object by passing the Runnable object as parameter
  • Start the Thread

/**
*
* @author paiman
*/
public class DispThread2 implements Runnable{

String msg;

public DispThread2(String msg) {
this.msg = msg;
}

@Override
public void run(){
for(int i=0; i<5;i++){
System.out.println(msg);
}

}

}


/**
*
* @author paiman
*/
public class ThreadTest2 {

public static void main (String[]args){
DispThread2 dt1 = new DispThread2("Thread");
DispThread2 dt2 = new DispThread2("Example");
Thread t1 = new Thread(dt1);
Thread t2 = new Thread(dt2);
t1.start();
t2.start();
}
}

Friday, November 20, 2009

Download Ebook: Java Thread Programming (Paul Hyde)


Professional Java developers who've come as far as they can without exploiting threads will find their skills bumped up a few notches by the time they finish Paul Hyde's Java Thread Programming. In a five-and-a-half-page first chapter, the book gives a basic concept briefing, then gets down to business with an example-rich education from the starting thread through inter-thread communication, thread groups, thread pooling, threads and Swing, and more. You'll get an experienced voice on how to gracefully exit from a thread -- and find out when to use the lead-between-the-eyes SureStop class instead. You'll even find out when multiple threads aren't a good idea. If you're serious about learning what it takes to do Java really, really well, this book is a good place to invest your time.

DOWNLOAD