How to create and start Java threads?

There are four common ways to create threads in Java.

1. Override the run() method of the Thread class.

There are two forms of expression: 1) the new Thread object anonymously overrides the run() method

package constxiong.concurrency.a006;

 /**
  * new Thread Object anonymous override run() method, start thread
  * @author ConstXiong
  */
public class TestNewThread {
	
	public static void main(String[] args) {
		//Create thread t, override run() method
		new Thread("t") {
			@Override
			public void run() {
				for (int i = 0; i <3; i++) {
					System.out.println("thread t > " + i);
				}
			}
		}.start();
	}

}

results of enforcement

thread t > 0
thread t > 1
thread t > 2

 

Inherit Thread object, override run() method

package constxiong.concurrency.a006;

/**
 * Inherit Thread class, override run() method
 * @author ConstXiong
 */
public class TestExtendsThread {
	
	public static void main(String[] args) {
		new ThreadExt().start();
	}

}

//ThreadExt inherits Thread and overrides the run() method
class ThreadExt extends Thread {

	@Override
	public void run() {
		for (int i = 0; i <3; i++) {
			System.out.println("thread t > " + i);
		}
	}
	
}

results of enforcement

thread t > 0
thread t > 1
thread t > 2

 

2. Implement the Runnable interface and rewrite the run() method.

There are two forms of expression: 1) new Runnable object, which anonymously overrides run() method

package constxiong.concurrency.a006;

/**
 * new Runnalbe Object anonymous override run() method, start thread
 * @author ConstXiong
 */
public class TestNewRunnable {

	public static void main(String[] args) {
		newRunnable();
	}
	
	public static void newRunnable() {
		//Create thread t1, override run() method
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i <3; i++) {
					System.out.println("thread t1 > " + i);
					try {
						Thread.sleep(1000L);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}, "t1").start();
				
		//Create thread t2, lambda expression set the execution code of thread
		//JDK 1.8 starts to support lambda expressions
		new Thread(() -> {
			for (int i = 0; i <3; i++) {
				System.out.println("thread t2 > " + i);
				try {
					Thread.sleep(1000L);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "t2").start();
	}
}

results of enforcement

thread t1 > 0
thread t2 > 0
thread t1 > 1
thread t2 > 1
thread t1 > 2
thread t2 > 2

 

Implement Runnable interface and rewrite run() method

package constxiong.concurrency.a006;

/**
 * Implement the Runnable interface and rewrite the run() method
 * @author ConstXiong
 */
public class TestImplRunnable {

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

///RunnableImpl implements the Runnalbe interface and rewrites the run() method
class RunnableImpl implements Runnable {

	@Override
	public void run() {
		for (int i = 0; i <3; i++) {
			System.out.println("thread t > " + i);
		}
	}
	
}

results of enforcement

thread t > 0
thread t > 1
thread t > 2

 

3. Implement the Callable interface and use the FutureTask class to create threads

package constxiong.concurrency.a006;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Implement the Callable interface and use the FutureTask class to create a thread
 * @author ConstXiong
 */
public class TestCreateThreadByFutureTask {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		//By constructing the FutureTask(Callable callable) constructor, FutureTask is created, and the Callable interface is implemented anonymously
		FutureTask<String> ft = new FutureTask<String>(new Callable<String>() {
			@Override
			public String call() throws Exception {
				return "ConstXiong";
			}
		});
		
		//Lambda implementation
//		FutureTask<String> ft = new FutureTask<String>(() ->  "ConstXiong");
		
		new Thread(ft).start();
		System.out.println("Execution result:" + ft.get());
	}
}

results of enforcement

Execution result: ConstXiong

 

IV. use thread pool to create and start threads

package constxiong.concurrency.a006;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Start threads in the way of thread pool
 * @author ConstXiong
 */
public class TestCreateThreadByThreadPool {

	public static void main(String[] args) {
		// Using the tool class Executors to create a single thread pool
		ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
		//Submit to perform task
		singleThreadExecutor.submit(() -> {System.out.println("Single thread pool execution task");});
		//Close thread pool
		singleThreadExecutor.shutdown();
	}
}

results of enforcement

Single thread pool execution task


 

 

All resources are summarized in the public address.



 

Keywords: Programming Java Lambda JDK

Added by jkmcgrath on Wed, 27 Nov 2019 16:39:13 +0200