• Google+
  • Twitter
  • YouTube
  • RSS
  • Facebook

Java Multithreading: Starting Threads (Video Tutorial Part 1)

Does multithreading seem like a black art to you? This is the first part of an advanced Java tutorial on multithreading that hopefully will help you out. In this tutorial we look at the two ways of starting a thread in Java.

This is an advanced tutorial, and as such I assume that you’re OK with extending classes, implementing interfaces and so on.

After starting the video, click the maximise button to make it fullscreen so you can see the code!

Code Examples For This Tutorial

Starting threads by extending the Thread class:

class Runner extends Thread {

	@Override
	public void run() {
		for(int i=0; i<5; i++) {
			System.out.println("Hello: " + i);
			
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
}


public class Application {

	
	public static void main(String[] args) {
		Runner runner1 = new Runner();
		runner1.start();
		
		Runner runner2 = new Runner();
		runner2.start();

	}

}

Starting threads using the Thread class directly:

class Runner implements Runnable {

	@Override
	public void run() {
		for(int i=0; i<5; i++) {
			System.out.println("Hello: " + i);
			
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
}


public class Application {

	
	public static void main(String[] args) {
		Thread thread1 = new Thread(new Runner());
		thread1.start();
	}

}

Starting threads using the Thread constructor with anonymous classes:


public class Application {

	
	public static void main(String[] args) {
		Thread thread1 = new Thread(new Runnable() {

			@Override
			public void run() {
				for(int i=0; i<5; i++) {
					System.out.println("Hello: " + i);
					
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
			
		});
		
		thread1.start();
	}

}

Learn to program Java Swing with my complete video course - desktop programming and applets. Includes 7 free videos. Click here for details.