Java Multithreading Basics

Source: Internet
Author: User

Click here to access gitpage, color lot Better dot

What is a thread

A thread is the smallest unit that the operating system can perform operations on. It is included in the process and is the actual operating unit of the process. A thread refers to a single sequential control flow in a process in which multiple threads can be concurrent and each thread performs different tasks in parallel.

Above is the explanation of the thread on the network, and you can see that the thread has the following characteristics:
-is included in the process, then the question comes: what is a process? The university teacher asked the same question, and I answered in my seat: the running program. Baidu Encyclopedia process is a computer program on a data set on a running activity, the system is the basic unit of resource allocation and scheduling, is the basis of the operating system structure.
-Threads are a single sequential control flow, and in plain terms the code executed in a thread is deterministic in order, and every step of the execution is deterministic, with no uncertainties.
-Threads can execute concurrently, and different tasks in a Java process do not have to wait for each other, and common scenarios include blocking IO, network communication, interface interaction, and so on.

Basic syntax for threads

There are two ways to create a thread in Java and perform a task, inheriting the Thread class or implementing the Runnable interface and overriding the run() method.

Inherit thread
class OneThread extends Thread {    int sleep;    OneThread(int sleep) {        this.sleep = sleep;    }    @Override    publicvoidrun() {        while (true) {            System.out.println("大家好,我是一个线程,我的名字叫:" + getName());            try {                TimeUnit.MILLISECONDS.sleep(sleep);            catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

To run write a thread's task in a method, feel free to do so!
To start a thread:

new OneThread(411);oneThread1.run();

Sorry, above is the wrong way to start the thread, it is important to invoke the start() method:

new OneThread(411new OneThread(557);oneThread1.start();oneThread2.start();

Interested WA can go on their own to perform a look;

Implementing the Runnable Interface
class OneRunnable implements Runnable {   int sleep;   OneRunnable(int sleep) {       this.sleep = sleep;   }   @Override   publicvoidrun() {       while (true) {           System.out.println("大家好,我是一个线程,我的名字叫:" + Thread.currentThread().getName());           try {               TimeUnit.MILLISECONDS.sleep(sleep);           catch (InterruptedException e) {               e.printStackTrace();           }       }   }}

Look carefully at the difference , the difference is not very haha.
How do I start it?

new Thread(new OneRunnable(411)).start();new Thread(new OneRunnable(557)).start();
Why are both available?

Let's look at Thread one of the constructor methods of the class:

publicThread(Runnable target) {    // 线程的默认名字就是这么来的    init(null"Thread-"0);}privatevoidinit(ThreadGroup g, Runnable target, String name,                      long stackSize, AccessControlContext acc) {...  this.target = target;...}

Threadthe objects are saved to the object when the object is constructed Runnable target , and then what? Looking back at the method of creating threads above found, the strange place isrun()

@Overridepublicvoidrun() {    ifnull) {        target.run();    }}

The truth is that the Thread default run method is called target.run() . This is why Thread both inheritance and implementation Runnable can create threads.
The attentive WA will notice that there is Thread.run() @Override , why?

publicclass Thread implements Runnable {...}

Threadis also Runnable an implementation class.

The state of the thread

New

A new thread object was created.new Thread()

Can run

Also called ready state. After the thread object is created, the method is called start() to enter the operational state. At this point, the thread can be executed at any time, waiting for the thread to dispatch check to get CPU

Run

The CPU time slice is obtained in the running state of the thread, executing the program code

Blocking

A blocking state is one in which a thread abandons the use of the CPU for some reason, and pauses the operation. Know that the thread is in a running state. There are three cases of blocking:
-Wait for blocking: The running thread executes the o.wait() method, and the JVM places the thread in the waiting queue.
-Synchronous blocking: When a running thread acquires a synchronization lock on an object, if the lock of the object is occupied by another thread, the JVM will put the nickname into the lock pool.
-Other blocking: a running thread execution Thread.sleep(long ms) or t.join() method, or when an I/O request is made, the JVM blocks the thread.

Death

The thread run() ends or encounters one, ending the thread's life cycle. The thread of death cannot be resurrected.

Shares

In a multithreaded environment, things are not controllable if there is no limit to accessing public resources together with multiple threads. Specific examples are not listed, we all understand.
Therefore, in a multithreaded environment, we need a way to control resources in the critical moment can only be a single thread in turn, not together.

Volatile

If a domain is declared volatile , all read operations can see this modification as long as a write is generated for the domain.
In a 64-bit JVM, the read and write of long and double are not atomic, please add volatile .

Lock

Manual locking and release, it's flexible.

publicintnext() {   lock.lock();   try {       ++ currentEvenValue;       Thread.yield();       ++ currentEvenValue;       return currentEvenValue;   finally {       lock.unlock();   }}

Be sure to finally release the return statement before releasing the lock, otherwise it is not completely atomic.

Synchronized

The most common way to lock. Enables code atomicity within the synchronization block to execute.

// 同步方法publicsynchronizedvoidtest() {...}// 同步块synchronized(obj) {...}
What's the lock?

The only thing that can be locked is the object, so what is it like above lock and synchronized locked? is the current object this . In fact, the whole process is that when thread 1 executes to the synchronous method, it gets the lock of the object, resumes execution if it can get it, and releases the lock at the end of execution, waits for another thread to release the lock if the lock is already occupied by another thread.
So the following code is executed?

 Public  class synctask {     Public synchronized void F1() {System.out.println ("F1 start");Try{TimeUnit.SECONDS.sleep (2); }Catch(Interruptedexception e)        {E.printstacktrace (); } System.out.println ("F1 End"); } Public synchronized void F2() {System.out.println ("F2 start"); } Public Static void Main(string[] args) {Synctask task =NewSynctask ();        Executorservice Executorservice = Executors.newcachedthreadpool ();        Executorservice.execute ((), task.f1 ());        Executorservice.execute ((), TASK.F2 ());    Executorservice.shutdown (); }}output:f1 STARTF1 endf2 Start

f1() f2() The locks here and all are the objects themselves, so thread 1 f1() gets the lock when it executes first, task and thread 2 executes f2() to request that the lock waits only when it appears as if it were executed sequentially.
With a little bit of processing, we can see different situations:

 Public  class synctask {Object A =NewObject (); Public void f3(){synchronized(a) {System.out.println ("F1 start");Try{TimeUnit.SECONDS.sleep (2); }Catch(Interruptedexception e)            {E.printstacktrace (); } System.out.println ("F1 End"); }    } Public synchronized void F2() {System.out.println ("F2 start"); } Public Static void Main(string[] args) {Synctask task =NewSynctask ();        Executorservice Executorservice = Executors.newcachedthreadpool ();        Executorservice.execute ((), task.f3 ());        Executorservice.execute ((), TASK.F2 ());    Executorservice.shutdown (); }}OUTPUT:F1 STARTF2 STARTF1 End

You can see that the thread is executing at the same time. Because thread 1 locks the object at this time a , the thread 2 locks on the object task , and there is no conflict between the two without waiting.
So what's going to happen next? WA, try it yourself.

publicclass SyncTask {    Object b;    publicvoidf3(){        synchronized (b) {            System.out.println("f1 start");            try {                TimeUnit.SECONDS.sleep(2);            catch (InterruptedException e) {                e.printStackTrace();            }            System.out.println("f1 end");        }    }    ...}
Some small point daemon threads for threads

Java threads have two types of user threads and daemons .
The so-called daemon thread is a thread of a generic service that the user program provides in the background at runtime, such as a garbage collection thread for garbage collection. This type of thread is not an integral part of the user thread, but a "service thread" that serves the service.

// 设置守护线程thread.setDaemon(true);

Places to be aware of:
- thread.setDaemon(true) must be thread.start() set before, otherwise it will run out an exception. You cannot set a running regular thread as a daemon thread.
-The thread that is generated in the daemon thread is also the daemon thread.
-Our own daemon threads should avoid accessing some intrinsic resources like files, databases, because the daemon will terminate immediately after the JVM does not have a user thread.
For the 2nd we can Thread prove by the source of the class:

class Thread {  init() {    ...    this.daemon = parent.isDaemon();    ...  }}
Thread Priority

The thread priority value is 1-10, and the higher the priority.
The priority of threads does not guarantee the order in which threads are executed. However, high-priority threads have a higher probability of getting CPU resources, and the lower priority is not a chance to execute.

thread.setPriority(10);

Java Multithreading Basics

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.