The---Multithreading Foundation of Java Multithreading Learning Summary

Source: Internet
Author: User
Tags thread class volatile

1. Thread-related concepts

1), thread-to-process differences

A thread is the smallest unit of operating system scheduling, also called a lightweight process, and a process is an application in the operating system that can create multiple threads in a process.

2), Context switch

We know that modern processors are multicore, several cores can only handle several threads at the same time, multi-threaded execution program appears to be at the same time, in fact, the CPU in a number of threads quickly switching between the execution, which involves the switch between the top and bottom, the so-called context switch refers to a thread t is allocated time slice ran out, The thread's information is saved, the CPU executes another thread, and the CPU reads the thread t's information and continues the T process.

2. Thread Implementation method

1), inherit the thread class

Because of the single inheritance of the class, the implementation of this way can no longer inherit other threads, there are limitations, high coupling degree.

 Public class extends thread{    @Override    publicvoid  run () {        Super. Run () ;        System.out.println ("I inherited the thread class ...");}    }

2), implement Runnable interface

Most are implemented in this way and are flexible, overriding the run () method, and the run () method has no return value.

3), implement callable interface

If you want to get to the execution of the thread, that way, it is the difference between implementing the Runnable interface is to rewrite the call () method, the call () is a return value, the returned object is the execution result of the task, It can be received using the implementation class Futuretask of the future interface, and the Get () method is called to get to the execution result. In addition, the call () method throws an exception, and the run () method cannot throw an exception

Public class Test {      Public Static voidMain (string[] args)throwsException {Thread thread1=NewMyThread ();        Thread1.start (); Thread thread2=NewThread (Newmyrunnable ());        Thread2.start (); Callable Callable=Newmycallable (); Futuretask<String> future =NewFuturetask<>(callable); Executorservice Executorservice=Executors.newsinglethreadexecutor ();        Executorservice.submit (future);        System.out.println (Future.get ());    Executorservice.shutdown (); }    Static classMyrunnableImplementsrunnable{@Override Public voidrun () {System.out.println ("I realized the Runnable interface ..."); }    }    Static classMycallableImplementscallable{@Override PublicString Call ()throwsException {return"I realized the callable interface ..."; }    }}

Execution Result:
  I inherited the thread class ...
I realized the Runnable interface ...
I realized the callable interface ...

3. Thread Status

Depending on the state inner class of the thread class in the JDK, the thread has 6 states, and the next time the interviewer asks you the thread has several states, you can have a very strong answer: 6, as shown in the left, and the right is the transition between thread states.

Note here that the thread is blocked while waiting for the thread state to enter the Synchronzed method or synchronized block, while waiting to enter the lock lock is waiting or time_waiting, Because lock is implemented with Locksupport (source has not studied).

The test is as follows:

 Public class MyService {public   static synchronized void ServiceMethod1 () {
try{
      System.out.println (Thread.CurrentThread (). getname+ "entered the business Method");
Thread.Sleep (millis:1000);
} catch (Execption e) {
E.printstacktrace ();
}  
}

   Public Static void serviceMethod2 () {
 New Reentrantlock (); Reentrantlock.lock (); System.out.println (Thread.CurrentThread (). GetName ()+ "into the Business Method");
try {
Thread.Sleep (1000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
Reentrantlock.unlock ();

}
}
 Public classMyThread1extendsthread{@Override Public voidrun () {myservice.servicemethod1 ();} Public classMyThread2extendsthread{@Override Public voidrun () {myservice.servicemethod1 ();}} Public classMyThread3extendsthread{@Override Public voidrun () {myservice.servicemethod2 ();}} Public classMyThread4extendsthread{@Override Public voidrun () {myservice.servicemethod2 ();}} Public classThreadstatustest { Public Static voidMain (string[] args) {test1 (); Test2 ();} Public Static voidtest1 () {MyThread1 T1=NewMyThread1 (); T1.setname (A); T1.start (); MyThread2 T2=NewMyThread2 (); T2.setname ("B"); T2.start (); System.out.println ("Status of T2:" +t2.getstate ()); }  Public Static voidtest2 () {MyThread3 T3=NewMyThread3 (); T3.setname (A); T3.start (); MyThread4 T4=NewMyThread4 (); T4.setname ("B"); T4.start (); System.out.println ("Status of T4:" +t4.getstate ()); }}

Test1 () operation Result:
A entered the business method
T2 Status: RUNNABLE
B entered the business method

Test2 () operation Result:
a entered the business method
T4 Status: RUNNABLE
B entered the business method

4. Common methods

1), start () a way to start the thread, the thread calls the start () method, and the new state changes to the ready state in the runnable state, waiting for the CPU to allocate the time slice, which is the method of the thread class;

2), run () required to implement the logic written in the Run method, the thread obtains the time slice from the ready state to running, and automatically call the run () method, of course, the run () method can also be called directly, it is the normal method, and thread-independent;

3), sleep (...) thread is changed from runnable state to timed_waiting state, calling this method throws a Interruptedexception exception, the thread itself has system resources, and waits for the time to wake up, and this is and wait () The main difference of the method;

4), Wait () notify () Notifyall () These three are all methods of the object class, which are used in conjunction with the thread state of the call to wait () method from running in runnable to waiting state. And this object does not occupy system resources, when the Notify () or Notifyall () method is called after the thread enters the ready state in the runnable, waiting for the CPU time slice;

5), join (...) waits for the thread object to be destroyed, and the thread state changes from runnable to waiting or timed_waiting;

6), interrupt (), the thread state becomes terminated;

7), yield (), the thread state is changed from running to ready, that is, from running to readiness, to the processor to indicate that it is willing to abandon the current CPU resources (make their own execution time), but give up time is uncertain, may just give up, and immediately get CPU time slice, All this method does not guarantee that the other thread must execute, the thread calling this method must not execute, but rather see whether the CPU is allocated a time slice, and it will only let the priority level not lower than the current thread execution, the priority is lower than it is no chance to execute.

5. Priority of Threads

The thread priority is 1-10 (from low to high), the default priority is 5, the number of time slices assigned by a high priority thread is lower than the priority, we can call the thread.setpriority (int) method to set the priority for the thread, and should be aware when setting the thread priority Contention for frequently blocked, such as hibernation, IO, database, and other tasks of the line thread executes set a higher priority, for computing-biased, such as the need for more CPU time or the bias operation of the thread should set a lower priority, to ensure that the processor is not exclusive.

6. Communication between threads

1),volatile synchronized

These two keywords can be used to communicate between threads, we know that each thread has its own working memory, and they have shared memory, the thread to a variable will first read the variable from the shared memory into its own private working memory, if a normal variable is modified and refreshed into the main memory when the timing of random, If the volatile variable (visibility and ordering), when another thread reads the variable, it is immediately flushed to the main memory, allowing the thread behind the read to see the change, which enables communication between the two threads.

Synchronized implements synchronization between threads, the B thread must wait until the a thread releases the lock to obtain the appropriate resources, which is a way of communicating between threads.

2), wait for notification mechanism wait () notify () Notifyall ()

A process starts with one thread, ends in another, the former is the producer, the latter is the consumer, the generator finishes production, informs the consumer to consume, and completes the communication between the two.

The relevant methods for waiting for notifications are

Wait (): the thread that calls the method enters the waiting state, only the other thread notifies or is interrupted to return, and after the method is called, the object's lock is freed;

Wait (long): timeout waiting for a period of time, here the parameter time is milliseconds, that is, waiting for up to n milliseconds, if there is no notification time-out return;

Wait (long,int): timeout is long milliseconds +int nanoseconds;

Notify (): Notifies a thread that the object is waiting to be returned from the Wait () method, while the thread acquires the lock of the object when it returns;

Notifyall (): Notifies all threads that are waiting on the object.

The above methods are all from the Java.lang.Object class, so you can call them as long as they are objects.

The Wait (), notify (), and Notifyall () calls require attention:

A, using Wait (), notify (), and notifyall () need to lock the calling object first;

B, after calling the Wait () method, the thread state is changed from running to waiting, and the current thread is placed in the object's wait queue;

After the C, notify () or Notifyall () method call, the waiting thread is still not returned from wait (), the thread that needs to call notify () or Notifyall () releases the lock, waiting for the thread to return from wait ();

The D, notify () method moves a waiting thread in the waiting queue from the wait queue to the synchronization queue, while the Notifyall () method waits for all threads in the queue to be moved to the synchronization queue, the thread-like

The state is changed from waiting to blocked;

E, returning from the Wait () method is the prerequisite for obtaining a lock on the calling object.

A thread calls the wait () method to release the held object monitor, enter the wait state, and then call the Notify () or Notifyall () method to wake up the A thread after the B thread has finished executing

3), pipeline input, output stream

Pipeline flows are specifically used for communication between threads, and the difference between ordinary character byte streams is that they operate on memory rather than hard disks.

There are four main implementations: byte stream: PipedOutputStream, PipedInputStream

Character stream:PipedWriter, Pipedreader

4), join (...)

Currently there are threads A and B, and if a executes the join () method, it means that the current thread a waits for the B thread to complete before it continues execution, that is, the communication between A and B is completed.

5), ThreadLocal

ThreadLocal, a thread variable, is a storage structure that takes a ThreadLocal object as a key and any object as a value. You can set a value by using the Set (T) method to get the previously obtained value by using the Get () method under the current thread.

Here's a snippet from the art of Java concurrent programming:

 Public classProfiler {Private StaticFinal threadlocal<long> time_threadlocal =NewThreadlocal<long>(){        protectedLong InitialValue () {returnSystem.currenttimemillis ();        }    };  Public StaticFinalvoidbegin () {time_threadlocal.Set(System.currenttimemillis ()); }         Public StaticFinalLongEnd () {returnSystem.currenttimemillis ()-time_threadlocal.Get(); }         Public Static voidMain (string[] args) throws Interruptedexception {Profiler.begin (); TimeUnit.SECONDS.sleep (1); System. out. println ("Cost :"+profiler.end () +"Mills"); }}

Operation Result:
COST:1005 Mills

Reference:The Art of Java concurrent programming

Finally, if you have written the wrong or bad place, please point out, thank you!

The---Multithreading Foundation of Java Multithreading Learning Summary

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.