How to use multi threading in Java code – There are two options implementing multi threading in Java; one is to extends Thread class and other is to implement Runnable Interface.
 
Extend Thread class and implement run() method.
invoke start() method available in super class Thread.
Also optionally use setName() method which can be useful tracking the thread object.
 
Complete class MultiThreading1.java can be found below;

public class MultiThreading1 extends Thread{

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MultiThreading1 t1 = new MultiThreading1();
		t1.setName("Thread1");
		t1.start();

		MultiThreading1 t2 = new MultiThreading1();
		t1.setName("Thread2");
		t2.start();
	}
	
	public void run(){
		// Do some task
		for (int j = 0; j < 5; j++) {
			System.out.println("Thread printing (name- "+this.getName()+") j="+j);
		}
	}
}

 
Implement Runnable class and implement run() method.
Create object for Thread class and invoke start() method available in super class Thread.
 
Complete class MultiThreading2.java can be found below;

public class MultiThreading2 implements Runnable{

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		MultiThreading2 obj1 = new MultiThreading2();
		Thread t1 = new Thread(obj1);
		t1.start();
		
		MultiThreading2 obj2 = new MultiThreading2();
		Thread t2 = new Thread(obj2);
		t2.start();
	}

	@Override
	public void run() {
		// Do some task
		for (int j = 0; j < 5; j++) {
			System.out.println("Thread printing (hashcode- "+this.hashCode()+") j="+j);
		}		
	}
}

 

 
For official Java Docs refer https://docs.oracle.com/javase/tutorial/essential/concurrency/
 
For further reading refer Java Programming Category posts.

How to use multi threading in Java code
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *