preface
This article mainly introduces the main methods of threads and the transformation between thread states,
Guys, take a look at the previous introduction to threads:
https://blog.csdn.net/u013351145/article/details/117742624
thread priority
We can set the priority of threads through setPriority(), and the level range between 1-10 can be selected
public final static int MIN_PRIORITY = 1; public final static int NORM_PRIORITY = 5; public final static int MAX_PRIORITY = 10; MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); // Set thread priority thread.setPriority(MIN_PRIORITY); thread.start();
If this range is exceeded, an IllegalArgumentException() exception will occur.
However, although threads can set priority, the order of execution is not based on priority
MyRunnable1 runnable1 = new MyRunnable1(); MyRunnable2 runnable2 = new MyRunnable2(); MyRunnable3 runnable3 = new MyRunnable3(); int i=1; while (i<6){ Thread thread1 = new Thread(runnable1); // Set thread priority thread1.setPriority(1); thread1.start(); Thread thread2 = new Thread(runnable2); // Set thread priority thread2.setPriority(5); thread2.start(); Thread thread3 = new Thread(runnable3); // Set thread priority thread3.setPriority(10); thread3.start(); i++; } public static class MyRunnable1 implements Runnable{ @Override public void run(){ System.out.println("Open thread 1"); } } public static class MyRunnable2 implements Runnable{ @Override public void run(){ System.out.println("Open thread 2"); } } public static class MyRunnable3 implements Runnable{ @Override public void run(){ System.out.println("Open thread 3"); } }
Execution result:
Open thread 2
Open thread 3
Open thread 3
Open thread 1
Open thread 2
Open thread 1
Open thread 3
Open thread 2
Open thread 1
Open thread 2
Open thread 3
Open thread 2
Open thread 3
Open thread 1
Open thread 1
Each execution result is different, but the one with higher priority will probably take the lead,
Because JAVA virtual machine adopts preemptive scheduling mode,
In short, you ordered a 10 yuan egg fried rice in my hotel and others ordered a 1W emperor fried rice
I will treat everyone equally. I mainly see who finds the table first and sits down and yells, "pretty boy, have a...".
The table is cpu time slicing, which is the key, not pretty
Thread state
Threads have six states
1.New
2.Runnable
3.Blocked
4.Waiting
5.Timed Waiting
6.Terminated
New: the state when the thread is created but not started
Runnable: you can think that the status is runnable after executing the start () method
Blocked: Generally speaking, the status of monitor lock is blocked
Waiting: there are many ways to enter the waiting state. For example, there is no wait method with Timeout set
Timed Waiting: similar to Waiting, the system wakes up again when the Waiting time comes
After the Terminated: run () method is executed, the thread will enter the stop state after exiting normally
Let's continue to look at the above figure. The New and Terminated states cannot be recovered unless a New thread is established.
Mainly the conversion between Runnable, Blocked, Waiting and Timed Waiting,
Runnable
After executing the start () method, the thread will be in this state,
Ways to enter the following states
Bocked status | get into | return |
---|---|---|
Synchronized locked code, unable to get monitor | Get the monitor lock |
Waiting status | get into | return |
---|---|---|
Execute join () | Thread end / interrupt of join | |
Execute wait () | ||
Execute locksupport park() | Execute locksupport unpark() |
Timed Waiting status | get into | return |
---|---|---|
Execute join (timeout) | Thread end / interrupt of join | |
Execute wait (timeout) | Time out | |
Execute locksupport parkNanos(timeout) | Execute locksupport unpark() | |
Execute locksupport parkUntil(timeout) |
Terminated status | get into | return |
---|---|---|
completion of enforcement | ||
An exception occurred |
Waiting and Timed Waiting
Bocked status | get into | return |
---|---|---|
notify () | ||
notifyAll() |
When entering the Bocked state, you cannot directly return to Waiting. You need to get the monitor lock and change to Runnable before entering.
Thread method
The pretty guy who comes into contact with the thread may be a little confused, but it doesn't matter
start()
Function: start thread
public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0) throw new IllegalThreadStateException(); /* Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ group.add(this); boolean started = false; try { start0(); started = true; } finally { try { if (!started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /* do nothing. If start0 threw a Throwable then it will be passed up the call stack */ } } } private native void start0(); /** * If this thread was constructed using a separate * <code>Runnable</code> run object, then that * <code>Runnable</code> object's <code>run</code> method is called; * otherwise, this method does nothing and returns. * <p> * Subclasses of <code>Thread</code> should override this method. * * @see #start() * @see #stop() * @see #Thread(ThreadGroup, Runnable, String) */ @Override public void run() { if (target != null) { target.run(); } }
The code is not long. The core is start0(). Then executing the run method will call the JVM_StartThread() method
Create another platform related OSThread instance.
Please refer to this article for specific details
Java thread creation underlying details
stop() (not recommended)
Function: stop the current thread
Stop the current thread, but we basically do not use this method, and the annotation in the source code is not recommended, saying that security cannot be guaranteed,
Normally, we don't stop a thread manually. For example, when the thread is writing a file, the stop method is executed to stop the thread, and the writing of the file is incomplete.
Therefore, in most cases, we use the interrupt method to stop the thread.
@Deprecated public final void stop() { SecurityManager security = System.getSecurityManager(); if (security != null) { checkAccess(); if (this != Thread.currentThread()) { security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION); } } // A zero status value corresponds to "NEW", it can't change to // not-NEW because we hold the lock. if (threadStatus != 0) { resume(); // Wake up thread if it was suspended; no-op otherwise } // The VM can handle all thread states stop0(new ThreadDeath()); }
interrupt ()
Function: notify the current thread to stop
interrupt is different in that it notifies the stopped thread, while for the thread to be stopped
You can choose to stop immediately or after a period of time. Of course, you can also choose to refuse execution.
So it's just a notice. Whether I do it or not depends on my mood,
Of course not so capricious,
In fact, Java hopes that programs can inform each other and cooperate with each other to manage threads, because if you don't know what the other party is doing, it may cause some safety problems to stop threads rashly
public void interrupt() { if (this != Thread.currentThread()) checkAccess(); synchronized (blockerLock) { Interruptible b = blocker; if (b != null) { interrupt0(); // Just to set the interrupt flag b.interrupt(this); return; } } interrupt0(); }
join()
Role: jump in line
The thread executing the join will execute first. After execution, other threads can continue to execute
Mainly check the thread status through the while loop. If the thread survives, call the wait() method to wait.
public final synchronized void join(long millis) throws InterruptedException { long base = System.currentTimeMillis(); long now = 0; if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (millis == 0) { while (isAlive()) { wait(0); } } else { while (isAlive()) { long delay = millis - now; if (delay <= 0) { break; } wait(delay); now = System.currentTimeMillis() - base; } } } // The effect of nanos can be understood as adding time public final synchronized void join(long millis, int nanos) throws InterruptedException { if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos >= 500000 || (nanos != 0 && millis == 0)) { millis++; } join(millis); }
sleep()
Function: sleep according to the specified time
public static void sleep(long millis, int nanos) throws InterruptedException { if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos >= 500000 || (nanos != 0 && millis == 0)) { millis++; } sleep(millis); }
yield()
Function: give way
yield will release CPU resources and let the thread with higher priority or the same level execute first
In fact, the bottom layer of sleep is also realized through yield
public static native void yield();
wait()
Function: wait
wait is a Object instance method. It must be invoked in synchronous or synchronous blocks, that is, the object lock must be obtained.
Because the essence is to use monitor lock implementation
public final void wait() throws InterruptedException { wait(0); }
sleep, yield and wait have similar functions, so they are more likely to appear during the interview.
Similarities:
1. Blocking threads
2. Respond to interrupt interrupt
difference:
1. The wair method needs to be protected in the synchrosize keyword, but sleep does not
2. A time must be defined in the sleep method (0 is allowed), while no time is allowed for wait
3.wait is the object class and sleep is the Thread class method.
notify()
Function: wake up
notify is an Object instance method that wakes up threads blocked by executing the wati method,
Of course, if there are many blocked threads, the notify method will wake up one at random.
notifyAll()
Function: wake up all
notifyAll is also an Object instance method, which can wake up all blocked threads,
Summary
The operation method of thread can be roughly understood without going deep into the code,
Generally speaking, thread communication, thread safety and thread pool are the key points in the interview process, and they are also the most asked by the interviewer.
Finally, if there is a lower old fellow, please contact me.