Thread state switching

Thread creation

How threads are created

When we call new Thread(), the JVM does not immediately create a corresponding system Thread < create Thread object on the heap >. Instead, when the start() method is called, The JVM creates a corresponding system thread with the clone system call (see pthread_create()). Because Java threads are ultimately mapped to system threads, we need to be careful when we need to create threads, especially when a large number of threads are needed:

  • An operating system limit on the number of threads
  • The overhead of creating, scheduling, and terminating threads
  • The consumption of system resources by the threads themselves (especially memory, the JVM needs to maintain a separate thread stack -Xss for each thread)

What is the difference between the start() and run() methods in Thread?

This question is often asked, but it can be a good indicator of an interviewer’s understanding of the Java threading model. The start() method is used to start the newly created thread, and the run() method is called inside start(), which does not have the same effect as calling run() directly. When you call the run() method, it will only be called in the original thread. No new thread will be started, so the start() method will start a new thread.

Reference: zhuanlan.zhihu.com/p/55819440

There are four ways to create a thread

import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; Public class NewThreadDemo {public static void main(String[] args) throws Exception {// The first method Thread Thread T1 = new Thread(){@override public void run() {system.out.println (" 新 的 :new Thread 1"); }}; t1.start(); TimeUnit.SECONDS.sleep(1); Runnable Thread t2 = new Thread(new Runnable() {@override public void run() {system.out.println (" Runnable Thread t2 = new Thread(new Runnable() {@override public void run() {system.out.println ( Thread 2"); }}); t2.start(); TimeUnit.SECONDS.sleep(1); Callable FutureTask<String> FutureTask = new FutureTask<>(new Callable<String>() {@override public String Call () throws Exception {String result = "新 式:new Thread 3"; return result; }}); Thread t3 = new Thread(futureTask); t3.start(); String result = futuretask.get (); String result = futuretask.get (); System.out.println(result); TimeUnit.SECONDS.sleep(1); / / a fourth way the thread pool ExecutorService pool = Executors. NewFixedThreadPool (5); Future<String> future = pool.submit(new Callable<String>(){ @Override public String call() throws Exception { String Result = "new Thread 4"; return result; }}); pool.shutdown(); System.out.println(future.get()); }}Copy the code

Runnable or Thread?

We all know that we can implement threads by inheriting the Thread class or calling the Runnable interface. The question is, which is better? When is it used? This question is easy to answer if you know that Java does not support multiple inheritance of classes, but allows you to call multiple interfaces. So if you want to inherit from another class, of course call the Runnable interface.

What is the difference between Runnable and Callable in Java?

Runnable and Callable both represent tasks that are to be executed in different threads. Runnable has been available since JDK1.0, Callable was added in JDK1.5. The main difference is that Callable’s Call () method can return values and throw exceptions, while Runnable’s Run () method does not. Callable can return a Future object loaded with computed results.

Thread to suspend

Thread.sleep() (sleep, no lock release)

Thread-class methods.

The sleep() method requires a specified amount of time to wait. It allows the thread currently executing the statement to pause and block for a specified amount of time, allowing other threads of the same or higher priority to execute, as well as lower priority threads. But the sleep() method does not release the “lock flag,” which means that if a synchronized block is present, other threads still cannot access the shared data.

public class TestThreadSleep implements Runnable{ public static void main(String[] args) { TestThreadSleep runnable = new TestThreadSleep(); Thread thread = new Thread(runnable); thread.start(); } @Override public void run() { System.out.println("i am sleep for a while!" ); try { Date currentTime = new Date(); long startTime = currentTime.getTime(); Thread.sleep(4000); currentTime = new Date(); long endTime = currentTime.getTime(); System.out.println(" sleep time: "+(endtime-starttime)+"ms"); } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code

Thread.join () (main thread waiting for child threads)

Thread object instance method.

Wait for the thread calling the JOIN method to terminate before continuing. Such as: t.j oin (); // This is used to wait for the t thread to finish. If this is not used, main will finish.

In many cases, the main thread creates and starts the thread, and if there is a lot of time-consuming computation in the child thread, the main thread will often end before the child thread ends. In this case, if the main thread wants to wait until the child thread completes, for example, processing data, the main thread uses join() to retrieve the value in the data. The join() method waits for the thread object to be destroyed.

package concurrent; public class TestJoin { public static void main(String[] args) { Thread thread = new Thread(new JoinDemo()); thread.start(); for (int i = 0; i < 20; I ++) {system.out.println (" main thread "+ I +" time execute! ); If (I >= 2) try {// the t1 thread is merged into the main thread, and the main thread stops the execution process and executes the T1 thread until the completion of the T1 execution. thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } } } class JoinDemo implements Runnable { @Override public void run() { for (int i = 0; i < 10; I ++) {system.out.println (" thread 1 executes on "+ I +"! ); }}}Copy the code

Thread.yield()

Thread-class methods.

Yield () simply causes the current thread executing the statement to return to the executable state **, **** so a thread executing yield() may be executed as soon as it enters the executable state. **yield() gives only threads of the same or higher priority a chance to execute. Instead of putting the thread into a blocking state, invoking yield puts the thread back into a ready state, where it waits to regain CPU execution time, unlike the sleep method.

public static void main(String[] args) { Runnable runnable = () -> { for (int i = 0; i <= 100; i++) { System.out.println(Thread.currentThread().getName() + "-----" + i); if (i % 20 == 0) { Thread.yield(); }}}; New Thread(runnable, "stack length ").start(); New Thread(runnable, "small ").start(); }Copy the code

Blog.csdn.net/youanyyou/a…

Thread the interrupt

What is the difference between interrupt, interrupted and isInterrupted methods in Java?

Segmentfault.com/a/119000002…

Thread collaboration (Wait, notify, notifyAll)

The first thing to note is: Wait, notify, and notifyAll are different from sleep, yield, Join, Interrupt, suspend, Resume, and stop, which are methods specific to threads.

Lock pools and wait pools

Lock pool: Suppose thread A already owns the lock on an object (note: not A class), and other threads want to call A synchronized method (or block) of that object. Since these threads must acquire ownership of the lock before entering the synchronized method of the object, However, the lock on this object is currently owned by thread A, so these threads enter the lock pool on this object.

Wait pool: If thread A calls wait() on an object, thread A releases the lock on the object and enters the wait pool for that object

The difference between notify and notifyAll

  • If a thread calls an object’s wait() method, it is in that object’s wait pool, and the threads in the wait pool do not compete for the lock on that object.
  • When a thread invokes the notifyAll() or notify() methods of an object, the awakened thread enters the lock pool of the object, and the threads compete for the lock. That is, after notify is called, only one thread enters the lock pool from the wait pool, and notifyAll moves all threads in the wait pool to the lock pool, waiting for lock contention
  • A thread with a higher priority has a higher probability of competing for an object lock. If a thread does not compete for the object lock, it will remain in the lock pool and only return to the wait pool if the thread calls wait() again. The thread that contended for the object lock continues to execute until the synchronized block is finished, which releases the object lock, at which point the pool of threads continues to contend for the object lock.
  • After notifyAll is called, all threads are moved from the wait pool to the lock pool, and then participate in the lock competition. If the competition is successful, the execution will continue. If it is not successful, the thread will remain in the lock pool until the lock is released and participate in the lock competition again. Notify only wakes up one thread.
public class WaitNotifyCase { public static void main(String[] args) { final Object object = new Object(); @override public void run() {system.out.println (" Thread A is waiting to get lock"); synchronized (object) { try { System.out.println("thread A get lock"); TimeUnit.SECONDS.sleep(1); System.out.println("thread A do wait method"); object.wait(); System.out.println("wait end"); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { System.out.println("thread B is waiting to get lock"); synchronized (object) { System.out.println("thread B get lock"); try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } object.notify(); System.out.println("thread B do notify method"); } } }).start(); }}Copy the code

Reference: www.zhihu.com/question/37…

If you feel you have gained something, please click a “like” to share the useful knowledge with more people

## Welcome to the Nuggets: 5:30

## Follow wechat public account: 5:30 Society (Financial enlightenment of salarymen) ##