Java multi-threading on (four kinds of ways to create threads and thread scheduling and life-cycle comparison, thread)

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/zxdspaopao/article/details/101422731

        To the contents of this multi-threaded, and say something good, in fact, content can be more or less, where some of the basic concepts is not to say, I say a few I think the master key places, or not too much.

Thread

Four ways to create a thread

  1. Thread class inheritance
  2. Implement Runnable
  3. Implement Callable Interface
  4. Use the thread pool

Method 1: Thread class inheritance

  1. Defined subclass inherits the Thread class.
  2. Thread class run method overridden in subclasses.
  3. Create a Thread subclass object, namely to create a thread object.
  4. Call the thread object start: Start the thread calls the run method.
class Threads extends Thread{
	public void run(){
		for(int i = 0; i < 100; i++){
			if(i % 2 != 0){
				System.out.println(i);
			}
		}
	}
}
public class MyThread{
	public static void main(String[] args) {
		//创建线程
		Threads mt = new Threads();
		//启动线程
		mt.start();
	}	
}

About the Thread class method

  • void start (): start threads, and executes the object's run () method
  • run (): when the operation thread of execution is scheduled
  • String getName (): Returns the name of the thread
  • void setName (String name): Set the thread name
  • static Thread currentThread (): Returns the current thread. Thread subclass is in this, and the main thread is typically used for the implementation class Runnable
  • static void yield (): thread concession (currently executing thread is suspended, the opportunity to give priority to the implementation of the same or higher thread, if there is no queue with priority threads, ignore this method)
  • join (): When a program calling another thread of the stream join () method, the calling thread will be blocked until the join () method added up to join the thread executing the low-priority threads can also get to perform
  • static void sleep (long millis) :( a specified time: ms) to make the currently active thread to relinquish control of the CPU in the specified time period, so that other threads a chance to be executed, after re-queuing time. Throws an exception InterruptedException
  • The end of the thread is forced to lifetime, is not recommended: stop ()
  • boolean isAlive (): returns boolean, to determine whether the thread is still alive

Second way: implement Runnable

  1. Subclassing, implement Runnable.
  2. run method Runnable interface override sub-category.
  3. Thread by thread object creation of Parametric constructor.
  4. The subclass object passed to Runnable interface Thread class constructor as an actual parameter.
  5. Thread class method calls start: open thread calls the run method subclass of Runnable interface.
public class SecondThread implements Runnable {
	private int i;
	@Override
	public void run() {
		for(; i < 100 ; i++){
			//当线程类实现Runnable接口时,
			//如果想获取当前线程,只能用Thread.currentThread()方法
			System.out.println(Thread.currentThread().getName()
					+ " " + i);
		}
	}
	
	public static void main(String[] args) {
		for(int i = 0; i < 100; i++){
				System.out.println(Thread.currentThread().getName()
						+ " " + i);
				if(i == 20){
					SecondThread st = new SecondThread();
					new Thread(st, "线程1").start();
					new Thread(st, "线程2").start();
				}
		}
	}

}

Three ways: to achieve Callable Interface

  1. Subclassing, Callable implement the interface.
  2. Callable interface call method subclass override.
  3. Thread by thread object creation of Parametric constructor.
  4. The interface Callable subclass object passed as actual parameters to the Thread class constructor.
  5. Thread class method calls start: open thread, call the call subclass interface Callable.
//1.创建一个实现Callable的实现类
class NumThread implements Callable{
	//2.实现call方法,将此线程需要执行的操作声明在call()中
	@Override
	public Object call() throws Exception {
		int sum = 0;
		for(int i = 1; i <= 100; i++){
			if(i % 2 == 0){
				System.out.println(i);
				sum += i;
			}
		}
		return sum;
	}	
}

public class CallableTest {
	public static void main(String[] args) {
		//3.创建Callable接口实现类的对象
		NumThread numThread = new NumThread();
		//4.将此Callable接口实现类的对象作为传递到FutureTask构造器中,创建FutureTask的对象
		FutureTask futureTask = new FutureTask(numThread);
		//5.将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()
		new Thread(futureTask).start();
		
		//接收返回值
		try {
			//6.获取Callable中call方法中的返回值
			//get()返回值即为FutureTask构造器参数Callable实现类重写的call()的返回值
			Object sum = futureTask.get();
			System.out.println("总和为:"+sum);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
}

Callable compared to using Runnable:

  1. Compared run () method may return a value
  2. The method can throw an exception
  3. Support generic return value
  4. FutureTask need the help of the class, such as access to return results

Four ways: using a thread pool

Ideas: advance created multiple threads into the thread pool, direct access to the use, used up back in the pool. Avoid frequent create destruction, to achieve reuse. Similar life in public transport

public class ThreadPoolTest {
	public static void main(String[] args) {	
		//创建一个具有固定线程数(6)的线程池
		ExecutorService pool = Executors.newFixedThreadPool(6);
		//使用Lambda表达式创建Runnable对象
		Runnable target = () -> {
			for(int i = 0 ; i < 100; i++){
				System.out.println(Thread.currentThread().getName()+
						" 的i值为:"+i);
			}
		};
		//向线程池提交两个线程
		pool.submit(target);
		pool.submit(target);
		
		//关闭线程池
		pool.shutdown();
	}
}

The JDK 5.0 from the thread pool provides relevant API : ExecutorService and Executors

ExecutorService : real thread pool interface. Common subclass ThreadPoolExecutor

  • void Execute (Runnable Command) : mission / command, no return value, typically used to perform Runnable
  • < T> Future <T> Submit (Callable <T> Task) : perform a task, return values, again generally performed Callable
  • void the shutdown () : Close Connection Pool

The Executors : tools, thread pool class factory for creating and returns of different types of thread pool

  • Executors.newCachedThreadPool () : Creates a thread pool that creates new threads as needed
  • Executors.newFixedThreadPool (n- ); a reusable fixed number of threads of thread pool
  • Executors.newSingleThreadExecutor () : Only one thread to create a thread pool
  • Executors.newScheduledThreadPool (the n- ) : Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.

benefit:

  1. Improve the response speed (reducing the time to create a new thread)
  2. Reduce resource consumption (reuse threads in the thread pool, do not need to create each time)
  3. Easy to thread management

 

Having said that some people will question, those two threads run with it runs the who?

This was said with regard to the scheduling of the java thread

Java scheduling method

  1. With the priority of threads FIFO queue (first come, first served), using the time slice (for a period of time) strategy.
  2. High priority, use (high priority threads preempt CPU) preemptive priority scheduling strategy.

Thread priority

  • Thread priority level
    1. MAX_PRIORITY:10
    2. MIN _PRIORITY:1
    3. NORM_PRIORITY:5
  • The method involves
  1. getPriority (): Returns the thread priority value
  2. setPriority (int newPriority): change the priority of the thread
  • Explanation
  1. Priority inheriting the parent thread when the thread is created.
  2. Low priority but low probability of obtaining scheduling, not necessarily was only called after the high-priority thread.

 

Thread of the life cycle

Talking about the first look at the life cycle of the thread before several states

  • New: When the Thread object class or subclass is declared and created in a new thread object nascent state.
  • Ready: the thread in the new state is start (), the thread will enter the queue waiting for CPU time slice, at this time it has with the conditions of operation, but not assigned to CPU resources.
  • Run: When ready thread is scheduled and access to CPU resources, it went into operation, run () method defines the operations and functions of the thread.
  • Blocking: In some special cases, is artificially suspended or perform input and output operation, so that the CPU and temporarily suspend their execution, into the blocked state.
  • Death: thread to complete all of its work in advance or thread is forcibly suspended or abnormal lead to the end.

The figure is conditional relation between the state and the conversion of the five states triggered. Here do not program demonstrates,

Next article:

Java multi-threading under (thread synchronization, the introduction of the deadlock problem (synchronized & lock usage and differences) and avoid and communication thread (producer, consumer issues))

 

 

Guess you like

Origin blog.csdn.net/zxdspaopao/article/details/101422731