1. Create a thread

1.1 Inherits Thread class

NewThreadExtend

public class NewThreadExtend extends Thread { public NewThreadExtend(String name) { super(name); } @Override public void run() { while (! Interrupted ()) {/ / and interrupt (); With system.out.println (getName() + "the thread executes.. "); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { NewThreadExtend d1 = new NewThreadExtend("first-thread"); NewThreadExtend d2 = new NewThreadExtend("second-thread"); d1.setDaemon(true); // daemon thread d1.start(); d2.start(); // d1.stop(); D1.interrupt (); d1.interrupt(); }}Copy the code

NewThreadExtendAndDaemon

public class NewThreadExtendAndDaemon extends Thread { public NewThreadExtendAndDaemon(String name) { super(name); } @override public void run() {while(true) {system.out.println (getName() +" "); } } public static void main(String[] args) { NewThreadExtendAndDaemon d1 = new NewThreadExtendAndDaemon("first-thread");  NewThreadExtendAndDaemon d2 = new NewThreadExtendAndDaemon("second-thread"); d1.setDaemon(true); // Daemon thread d2.setdaemon (true); // daemon thread d1.start(); d2.start(); try{ Thread.sleep(2000); }catch (Exception e){ e.printStackTrace(); }}}Copy the code

NewThreadExtendAndInterrupt

public class NewThreadExtendAndInterrupt extends Thread { public NewThreadExtendAndInterrupt(String name) { super(name);  } @Override public void run() { while (! Interrupted ()) {/ / and interrupt (); With system.out.println (getName() + "the thread executes.. "); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { NewThreadExtendAndInterrupt d1 = new NewThreadExtendAndInterrupt("first-thread"); NewThreadExtendAndInterrupt d2 = new NewThreadExtendAndInterrupt("second-thread"); d1.start(); d2.start(); d1.interrupt(); }}Copy the code

NewThreadExtendAndStop

public class NewThreadExtendAndStop extends Thread { public NewThreadExtendAndStop(String name) { super(name); } @Override public void run() { for (int i = 0; i < 10; I++) {system.out.println (getName() + "the thread executed.. "); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { NewThreadExtendAndStop d1 = new NewThreadExtendAndStop("first-thread"); NewThreadExtendAndStop d2 = new NewThreadExtendAndStop("second-thread"); d1.start(); d2.start(); d1.stop(); // Has expired (@deprecated).}}Copy the code

1.2 Implementing the Runnable Interface

/ / public class NewThreadRunnable implements Runnable {@override public void run() {while(true) { System.out.println("thread running ..." ); } } public static void main(String[] args) { Thread thread = new Thread(new NewThreadRunnable()); thread.start(); }}Copy the code

Both need to override the run() method, but inheritance can only be inherited from a parent class, and the interface approach is decoupled and more flexible. The difference between Runnable and Thread in Java

1.3 Anonymous inner class approach

It’s easier and more useful when you only run it once

public class NewThreadAnonymousInner { /** anonymous1 extend thread start .. anonymous2 Runnable thread start .. anonymous1and2 extend thread start .. */ public static void main(String[] args) { anonymous1(); anonymous2(); anonymous1and2(); } public static void anonymous1() {new Thread(){@override public void run() { super.run(); } }.start(); } public static void anonymous2() {the new object is short for Implement new Thread(new Runnable() {@override public void run() { System.out.println("anonymous2 Runnable thread start .." ); } }).start(); } // The parent's Runnable run is overridden by the parent's Runnable run, which is overridden by the Thread's run anonymous1and2() { new Thread(new Runnable() { @Override public void run() { System.out.println("anonymous1and2 Runnable  thread start .." ); } }) { public void run() { System.out.println("anonymous1and2 extend thread start .. "); }; }.start(); }} // Run the anonymous1 extend thread start.. anonymous2 Runnable thread start .. anonymous1and2 extend thread start ..Copy the code

1.4 Thread Callable with return value

import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; Public class NewThreadCallable implements Callable<Integer> {similar to the run method @override public Integer Call () throws Exception {system.out.println (" Performing a tense calculation...." ); Thread.sleep(3000); return 1; } public static void main(String[] args) throws Exception { NewThreadCallable threadCallable = new NewThreadCallable(); FutureTask<Integer> task = new FutureTask<>(threadCallable); Thread t = new Thread(task); t.start(); // Call () starts with system.out.println (" I'll do something else... ); Integer result = task.get(); System.out.println(" thread execution result: "+ result); }}Copy the code

1.5 timer

import java.util.Timer; import java.util.TimerTask; public class ThreadTimerTask { public static void main(String[] args) { Timer timer = new Timer(); // source :public abstract TimerTask implements Runnable timer.schedule(new TimerTask() {@override public void run() { Println (" TimerTask is run"); }}, 0, 1000); }}Copy the code

Quartz is also available.

1.6 Implementation of thread pool

Public class NewThreadPool {public static void main(String[] args) {// Fixed thread pool threadPool1 = Executors.newFixedThreadPool(10); / / the length more than processing needs, flexible recycle the idle thread, if no recovery, new threads ExecutorService threadPool2 = Executors. NewCachedThreadPool (); for (int i = 0; i < 1000; i++) { threadPool1.execute(new Runnable() { @Override public void run() { System.out.println("threadPool1->"+Thread.currentThread().getName()); }}); } threadPool1.shutdown(); for(int i=0; i<1000; i++){ threadPool2.execute( new Runnable() { @Override public void run() { System.out.println("threadPool2->"+Thread.currentThread().getName()); }}); }}}Copy the code

Java thread pool four newCachedThreadPool newFixedThreadPool, newScheduledThreadPool, newSingleThreadExecutor

1.7 Spring implements multi-threading

  • @Async
@ Async method annotationCopy the code

Spring Boot series 2 Spring @Async Async thread pool usage summary

3.8 Implementation of Lambda expressions

Simple code, more convenient implementation, good concurrency support, high code performance,

public class LambdaThread { public static void main(String[] args) { List<Integer> values = Arrays.asList(10, 20, 30, 40); int res = new LambdaThread().add(values); System.out.println(" + res "); } public int add(List<Integer> values) { //values.parallelStream().mapToInt(i->i).sum(); //values.stream().foreach (system.out :: println); ParallelStream ().foreach (system.out :: println); forEach(system.out :: println); // You will find that the print results are unordered and different each time. Parallel // values.parallelstream ().foreachordered (system.out :: println); Integer return values.parallelstream ().mapToint (I -> I * 2).sum(); }}Copy the code

1.8 Difference between Thread and Runnable

If a class inherits Thread, it is not suitable for resource sharing. However, if the Runable interface is implemented, it is easy to implement resource sharing. Summary: Implementing the Runnable interface has advantages over inheriting the Thread class: 1) It is suitable for multiple threads of the same program code to handle the same resource; 2) It avoids the restriction of single inheritance in Java; 3) It increases the robustness of the program, code can be shared by multiple threads, code and data independence; 4) Thread pools can only be placed into classes that implement Runable or Callable, not directly into classes that inherit threads

1.9 pay attention to

  • The main method is actually a thread. In Java, all threads are started at the same time, and when and which are executed first depends on who gets the CPU resources first.
  • In Java, at least two threads are started each time a program runs. One is the main thread and the other is the garbage collector thread. Because every time a class is executed using a Java command, a JVM is actually started, and each JVM is starting a process in the operating system.

2. Multithreading risks

2.1 Activity problem

2.1.1 deadlock

Jconsole selects the process, then enters the thread, there is a button operation “deadlock detection” to check the deadlock condition.

CMD -> jsonCole -> Select process -> Thread -> Detect deadlockCopy the code

2.1.2 hunger

Restaurant line up to eat, a window, the new on the queue, do not go, there has been a row, hunger, caused by priority.

Causes: high-priority swallows all the lower priority thread CPU time slice is plugged in a permanent waiting to enter the state of the synchronized block. (a method with the lock, two threads waiting to enter, one into the things not finished out, after another has been waiting for a thread, it is also a hunger) waiting thread will never be awakened

How to avoid starvation: set proper priority —- setPriority() and try to solve the problem of using locks instead of —- synchronized

2.1.3 live lock

The two threads are constantly condescending to each other, and then occupy each other.(2 people log bridge, mutual way example)Copy the code

2.2 Performance Problems

Context switch (single CPU), time slice

2.3 Thread safety issues

    • Multithreaded environment
    • Multiple threads share a resource
    • Perform non-atomic operations on resources

Meeting these three points leads to thread-safety issues

— Organize them on the Internet