O'Reilly logo

Java Pocket Guide by Patricia Liguori, Robert Liguori

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 14. Concurrency

Threads in Java allow the use of multiple processors or multiple cores in one processor more efficiently. On a single processor, threads provide for concurrent operations such as overlapping I/O with processing.

Java supports multithreaded programming features with class Thread and interface Runnable.

Creating Threads

Threads can be created two ways, either by extending java.lang.Thread or by implementing java.lang.Runnable.

Extend the Class Thread

Extending class Thread and overriding the run( ) method can create a threadable class. This is an easy way to start a thread.

	class Comet extends Thread {
	  public void run( ) {
	    System.out.println("Orbiting");
	    orbit( );
	  }
	}

	Comet halley = new Comet( );

Remember that only one superclass can be extended, so a class that extends Thread cannot extend any other superclass.

Implementing the Interface Runnable

Implementing the Runnable interface and defining its run( ) method can also create a threadable class. Creating a new Thread object and passing it an instance of the runnable class creates the thread.

	class Asteroid implements Runnable {
	  public void run( ) {
	    System.out.println("Orbiting");
	    orbit( );
	  }
	}

	Asteroid maja = new Asteroid( );
	Thread majaThread = new Thread(maja);

A single runnable instance can be passed to multiple thread objects. Each thread performs the same task.

	Asteroid pallas = new Asteroid( );
	Thread pallasThread1 = new Thread(pallas);
	Thread pallasThread2 = new Thread(pallas);

Thread States

Enumeration Thread.state ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required