Concurrent learning in Java: multiple ways to create threads

Posted by hush on Fri, 10 Jan 2020 19:15:30 +0100

Multiple ways to create threads

  1. Inherit Thread class
  2. Implement the Runnable interface
  3. How anonymous inner classes work
  4. Method with return value
  5. timer
  6. Implementation of thread pool
  7. Implementation of Lambda expression

1, Inherit Thread class

public class Demo1 extends Thread{
	public Demo1(String name) {
		super(name);
	}
	@Override
	public void run() {
		while(!interrupted()) {
			System.out.println(getName()+"Thread started...");
			/*try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}*/
		}
			
		//super.run();
	}
	
	public static void main(String[] args) {
		Demo1 d1 = new Demo1("first");
		Demo1 d2 = new Demo1("second");
		
		//true is set to the guardian thread and false is set to the user thread. If the property is not set, the default is the user thread.
		//d1.setDaemon(true);
		//d2.setDaemon(true);
		d1.start();
		d2.start();
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Main thread started");	
		d1.interrupt();
		d2.interrupt();
	}
}

II. Implementation of Runnable interface

public class Demo2 implements Runnable{
	
	@Override
	public void run() {
		while(true) {
			System.out.println("Thread executed...");
		}
	}
	
	public static void main(String[] args) {
		
		Thread td1 = new Thread(new Demo2());
		td1.start();
	}
}

3, How anonymous inner classes work

public class Demo2 {
	

	public static void main(String[] args) {
		new Thread() {
			public void run() {
				System.out.println("Anonymous inner class thread 1 executed..");
			}
		}.start();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("Anonymous inner class thread 2 executed..");
			}
		}).start();
		
	//In this way, the sub is printed. If the runnable interface is rewritten and the subclass is rewritten at the same time, the subclass thread is executed
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("runnable");
			}
		}) {
			public void run() {
				System.out.println("sub");
			}
		}.start();
	}
}

4, Method with return value

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

public class Demo4 implements Callable<Integer>{

	@Override
	public Integer call() throws Exception {
		System.out.println("Calculation in progress..");
		Thread.sleep(1000);
		return 1;
	}
	
	public static void main(String[] args) throws  Exception {
		
		Demo4 d = new Demo4();
		FutureTask<Integer> task = new FutureTask<>(d);
		Thread td = new Thread(task);
		td.start();
		
		System.out.println("I'll do something else first");
		
		Integer result = task.get();
		System.out.println("The thread execution result is:" + result);
	}
}

Output results:
I'll do something else first
Calculation in progress
The thread execution result is: 1

5, Timer

import java.util.Timer;
import java.util.TimerTask;

public class Demo5 {

	public static void main(String[] args) {
		
		Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				//Implement scheduled tasks
				System.out.println("Scheduled task execution..");
			}
		},0,1000);
	}
}

6, Implementation of thread pool

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

public class Demo6 {

	public static void main(String[] args) {
		
		//Create a thread pool with 10 threads
		ExecutorService threadPool = Executors.newFixedThreadPool(10);
		//ExecutorService threadPool = Executors.newCachedThreadPool();
		for(int i = 0; i < 10; i++) {
			threadPool.execute(new Runnable() {
				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName());
				}
			});
		}
		
		threadPool.shutdown();
	}
}

7, Lambda expression implementation

import java.util.Arrays;
import java.util.List;

public class Demo7 {

	public int add(List<Integer> l) {
		l.parallelStream().forEach(System.out::print);
		//Results: 30 20 40 10 indicates that parallel stream is a parallel execution stream
		l.stream().forEach(System.out::print);
		//Result: 10 20 30 40 indicates that stream is not a parallel execution stream
		return l.parallelStream().mapToInt(a -> a).sum();
	}
	
	public static void main(String[] args) {
		List<Integer> l = Arrays.asList(10,20,30,40);
		int result = new Demo7().add(l);
		System.out.println("Sum result:"+result);
	}
}

 

 

Topics: Java Lambda