1.1 What is a thread?
Before understanding the thread must first understand what is the process, because the thread is a physical process. (Thread will not exist independently)
Process: the code is run on the data collection activity is the basic unit of system resource allocation and scheduling, thread is a path of execution process, a process will have at least one thread, multiple threads sharing process resources process.
Thread: cpu is the basic unit of assignment.
As can be seen from the above chart, there will be a process multiple threads, multiple threads shared heap and method area, but each thread will have its own stack and program counter.
Why do you want to stack and program counter to thread it private?
In front of said thread is the basic unit of execution cpu, cpu and generally use round-robin fashion polling occupied, so when the current thread cpu time slice used up, let the cpu, waiting for the next time their turn in the call .
That question came up, how the thread where the execution is to know before?
Before recording the program counter it is to allow the address to execute when the cpu, you can get to the position prior to the implementation of the program counter when the next time is executed again, continue down. (Program counter address is not recorded in the native method execution, it records the address java code execution), and the stack is the storage site of a local variable, once again after use
1.2 threads to create and run
Three ways: inheritance Thread, implement Runnable, use FuthreTask way (to achieve Callable Interface).
package com.nxz.blog.otherTest; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class TestThread { static class MyThread1 extends Thread { @Override public void run() { System.out.println("extend-Thread:"+this.getName()); } } static class MyThread2 implements Runnable { @Override public void run() { System.out.println("implements-Runnable:"+Thread.currentThread()); } } static class MyThread3 implements Callable<String> { @Override public String call() throws Exception { System.out.println("implements-Callable:"+Thread.currentThread()); return "Callable接口"; } } public static void main(String[] args) { MyThread1 t1 = new MyThread1(); t1.start(); Thread t2 = new Thread(new MyThread2()); t2.start(); FutureTask<String> futureTask = new FutureTask<>(new MyThread3()); new Thread(futureTask).start(); try { // 阻塞,等待执行完毕,并返回结果 String res = futureTask.get(); System.out.println(res); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println("main-Thread"); } }
The code above results:
extend-Thread:Thread-0 implements-Runnable:Thread[Thread-1,5,main] implements-Callable:Thread[Thread-2,5,main] Callable接口 main-Thread
After you create a thread calls the start method, representing the current thread already in the ready state (that is to say that the thread has already acquired other resources except cpu resources, waiting for execution cpu time slice), after obtaining the cpu resources, it is in the thread operating state, once the run method (for it extent thread) is finished, the thread is terminated state.
Use inheritance benefits: can be used directly in a run this method to get the current thread (the other two are some of the ways this is no getName, etc.), without the need Thread.currentThread ().
1.3 thread and wait for notification
The following three methods are methods Object class, common for all objects
①wait()
When a thread calls the wait () method, the thread will be blocked pending, know to be called notify / notifyAll or other thread calls intercept method interrupted this thread
②wait(long timeout)
On top of a table more than a timeout during the waiting period if no other thread wakes up (notify / notifyAll) the thread, the thread will still be automatically returned after exceeding the timeout time
③wait (long timeout, int nanos): two parameters, timeout milliseconds, nanoseconds nanos, wait (long timeout) method is called inside, only few nanoseconds for the second parameter, if the range is greater than 0, if less than one million (1,000,000 ns = 1 ms), then the timeout plus one second
public final void wait(long timeout, int nanos) throws InterruptedException { if (timeout < 0) { throw new IllegalArgumentException("timeout value is negative"); } if (nanos < 0 || nanos > 999999) { throw new IllegalArgumentException( "nanosecond timeout value out of range"); } if (nanos > 0) { timeout++; } wait(timeout); }
④notify()/notifyAll()
Wake threads on the same shared variable waiting difference: a wake-a, a wake up all
It should be noted:
* Wake false:
A thread can be changed to run state (that is, wake up) from a suspended state, even if the thread has not been called notify (), notifyAll () method to notify other threads, or is interrupted, or wait for the timeout, this is a false wake
(This is described in the US in the java concurrent programming, the feeling is not clear, some are looking for other information described: In multi-core processors, signal other threads may wake up multiple threads (blocked on the same condition variable thread), the result is, more thread to be awakened, after the implementation of a code logic before another thread will have problems after performing the same code again)
Example: In the following code, respectively producer and consumer, if in the case of a producer and a consumer (that is, single-threaded), there is no problem, there is no false wake up, if in a multithreaded environment, when a producer is completed, after calling notifyAll method will wake up all the other producers and consumers, after the completion of the first consumer spending, consumer spending in there, then there will be problems (that is, the emergence of false wake-up), the solution to this problem, is to consumers and producers in the conditional if (queue.size () == 1) and if (queue.isEmpty ()) instead while (queue.size () == 1) and while (queue.isEmpty ()), that is changed to cycle to determine when wake up is that each thread to re-determine eligibility
static Queue Queue; static class ProductThread the extends the Thread { @Override public void RUN () { the synchronized (Queue) { IF (queue.size () ==. 1 ) {// assume a target queue stores up the try { queue.wait () ; } the catch (InterruptedException E) { e.printStackTrace (); } } queue.add ( new new Object ()); queue.notifyAll (); } } } static class ConsumerThread extends Thread { @Override public void run() { synchronized (queue) { if (queue.isEmpty()) { try { queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } queue.poll(); queue.notifyAll(); } } }
1.4 waiting thread is finished join method
When you call the join method (which belongs to the Thread class), will be waiting thread is finished, while continuing to run down
example:
package com.nxz.blog.otherTest; public class TestThread002 { static class MyThread extends Thread{ @Override public void run() { System.out.println("myThread"); } } public static void main(String[] args) throws InterruptedException { MyThread t1 = new MyThread(); t1.setName("myThread"); t1.start(); //If the code is commented below, the output should be the main method is to try MyThread main-thread, // after the opening of the case main thread will wait for the main thread is finished t1, running down t1.join (); System.out.println ( "main-Thread" ); } }
1.5sleep method dormant
Static methods Thread in sleep (), when a thread calls sleep method, briefly let the cpu executive power (that is, not involved in the cpu scheduling), but the thread that owns the lock and other resources are not released, it different methods and wait
1.6 Let the cpu executive power yield method
Static methods Thread in yield (), when a thread calls Thread.yield (), the table name the current thread to give up the right to use the cpu, after the yield, the current thread in the ready state. Thread scheduler randomly selects one execution thread cpu time slices allocated from all of the threads comprising thread.
1.7 interrupt thread
java thread interrupts in a collaboration between the thread mode, the thread by setting the interrupt flag does not directly interrupt the thread, but the thread is interrupted according to the discretion of the interrupt flag.
void interruupt (): interrupt thread
boolean isInterrupted (): current detection are cars Eng is interrupted (call isInterrupted () method interrupt flag instances)
boolean interrupted (): detects whether the current thread is interrupted (internal thread is to get the current interrupt flag instead of calling interruupted () method of example interrupt flag)
1.8 thread context switching
Thread in a multithreaded programming are generally larger than the number of the number of cpu, cpu and each used by only one thread at a time. In order to allow users to feel really performed simultaneously, resources allocation cpu time slice rate using the side polling.
Context switching: After a thread is finished using the time slice, the cpu resources to give other threads, and thread state into a ready state.
1.9 thread deadlock
Multiple threads in the implementation process, due to competition for resources caused by waiting for each state, as there are no other factors, the thread will wait, can not continue to run.
Deadlock conditions are: 1, 2 mutually exclusive, and holds the request resource 3, 4 can not be denied, waiting loop
1.10 Daemon threads and user threads
Daemon threads: Similar to garbage collection thread
User threads: main function is activated, the user is a simple thread
jvm stop timing: after the user completes all threads, jvm will stop (with or without a daemon thread)
1.11ThreadLocal
After creating a ThreadLocal variable, multiple threads operating variable, in fact, operate their own local memory variables, that is, each thread will copy variable to its own local memory.
THreadLocal is how threads and associate it?
ThreadLocal is actually an empty shell when calling the ThreadLocal set or get method, the internal method is set by the value placed threadlocals variables of the calling thread (ThreadLocal.threadLocalMap), that is not the existence of local variables ThreadLocal instance, but credited Thread in threadlocals in.
public void set (T value) { Thread T = Thread.currentThread ();
// When ThreadLocal set methods when invoked, the fact is to obtain the current thread Thread ThreadLocalMap variables, if the variable is null, a new ThreadLocalMap, If the variable exists, between the current thread and the value stored in the custom map (ThreadLocalMap) ThreadLocalMap map = getMap (t); IF (map =! null ) map.set ( the this , value); the else CreateMap (t, value); } // getMap source can be seen from the fact that the current thread acquired the threadLocals variable ThreadLocalMap getMap (the thread T) {
return t.threadLocals; } void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }
public T get () {
// get the ThreadLocal the method, it is also obtained in the current thread Thread threadLocals variables (i.e. ThreadLocalMap types of data) Thread T = Thread.currentThread (); ThreadLocalMap Map = the getMap (T); IF (Map =! null ) { ThreadLocalMap.Entry E = map.getEntry ( the this ); IF (E =! null ) { @SuppressWarnings ( "an unchecked" ) T Result = (T) e.Value; return Result; } } returnsetınitialvalu A (); }