Basic Overview of Java Multithreading

Source: Internet
Author: User

1.1. Concept:

     Process: The process is the basis of the operating system structure, is the execution of a program, is a program and its data re-processor on the sequential execution of the activity, is a program to run on a data set, it is the system of system resource allocation and scheduling of the smallest unit.

    Threads : Can be understood as a different execution path for a program, which is the smallest unit of program execution flow. A thread is an entity in a process, a basic unit that is dispatched and dispatched independently by the system, which does not own system resources and has only a bit of resources necessary to run, but it can share all the resources owned by the process with other threads of the same process. One thread can create and revoke another thread, which can be executed concurrently between multiple threads in the same process. Because of the mutual constraints between threads, the thread is running in a discontinuous. Threads also have three basic states of readiness, blocking, and running. A ready state is a thread that has all of the conditions running, is logically capable of running, is waiting on a processing machine, and a running state is a thread-owning processor that is running; a blocking state is a thread waiting for an event, such as a semaphore, to be logically unenforceable. Each program has at least one thread, and if the program has only one thread, it is the program itself.

1.2. Use multithreading

    

1  PackageSoarhu;2 3 /**4 * Created by Huaox on 2017/4/17.5  *6  */7  Public classTest {8      Public Static voidMain (string[] args) {9 System.out.println (Thread.CurrentThread (). GetName ());Ten     } One}

Output Result: Main

As you can see, the thread on which the main method resides is a thread called Main.

There are three main ways to create threads: Inherit the thread class, and implement the runnable and callable interfaces, respectively.

1.2.1: Inherit thread

Thread is defined in the JDK document as: public class Thread implements Runnable

The biggest limitation of using inherited from thread is the inability to implement multiple inheritance, so you can implement the Runnable interface or the callable interface.

1  PackageSoarhu;2 3 /**4 * Created by Huaox on 2017/4/17.5  *6  */7 8 classThreadTestextendsthread{9 Ten @Override One      Public voidrun () { ASystem.out.println ("ThreadTest Run Method:" +Thread.CurrentThread (). GetName ()); -     } - } the  -  Public classTest { -      Public Static voidMain (string[] args) { -System.out.println ("Main method:" +Thread.CurrentThread (). GetName ()); +Thread thread =Newthreadtest (); - Thread.Start (); +SYSTEM.OUT.PRINTLN ("End!!!"); A     } at}

Output Result:

Main Method:main

End!!!
ThreadTest Run method:thread-0

From the output you can tell that the order of code execution between threads is not controllable or that the order of invocation is irrelevant.

1.2.2: Implementing the Runnaball Interface

  

 PackageSoarhu;/*** Created by Huaox on 2017/4/17. **/classThreadTestImplementsrunnable{@Override Public voidrun () {System.out.println ("ThreadTest Run Method:" +Thread.CurrentThread (). GetName ()); }} Public classTest { Public Static voidMain (string[] args) {System.out.println ("Main method:" +Thread.CurrentThread (). GetName ()); Thread Thread=NewThread (Newthreadtest ());        Thread.Start (); System.out.println ("End!!!"); }}

The output is consistent with the previous example.

1.2.3: Implementing the Callble Interface

The callable interface is similar to runnable, but Runnable does not return a result and cannot throw an exception that returns a result, and callable can return a value that can be obtained by the future. Examples are as follows

 PackageSoarhu;Importjava.util.concurrent.*;/*** Created by Huaox on 2017/4/17. **/classThreadTestImplementsCallable<string>{@Override PublicString Call ()throwsException {System.out.println ("ThreadTest Run Method:" +Thread.CurrentThread (). GetName ()); Try{TimeUnit.MILLISECONDS.sleep (3000); } Catch(interruptedexception E1) {e1.printstacktrace (); }        return"Hello"; }} Public classTest { Public Static voidMain (string[] args)throwsexecutionexception, interruptedexception {//The first way:      /*Executorservice executor = Executors.newcachedthreadpool ();        future<string> future = Executor.submit (New ThreadTest ());        SYSTEM.OUT.PRINTLN ("Result:" + future.get ()); Executor.shutdown ();*/      //The second way:Futuretask<string> Futuretask =NewFuturetask<string> (Newthreadtest ()); Thread Thread=NewThread (Futuretask);        Thread.Start (); System.out.println ("Result:" +futuretask.get ()); }}

Output Result: Hello

1.2.4, Thread safety

    

 PackageSoarhu;/*** Created by Huaox on 2017/4/17. **/classThreadTestImplementsrunnable{Private intCount = 5; @Override Public voidrun () { while(count-->0) System.out.println (Thread.CurrentThread (). GetName ()+ "count:->" +count); }} Public classTest { Public Static voidMain (string[] args) { for(inti = 0; I < 3; i++) {            NewThread (NewThreadTest (), i+ ""). Start (); }    }}

Output Result:

0 count:-> 4
2 count:-> 4
1 count:-> 4
1 count:-> 3
1 count:-> 2
1 count:-> 1
1 Count:-> 0
2 count:-> 3
2 count:-> 2
2 count:-> 1
2 Count:-> 0
0 count:-> 3
0 count:-> 2
0 count:-> 1
0 count:-> 0

The count variable in the program is a member variable, and concurrency problems occur if multiple threads are accessing it at the same time, but now the program does not have a security problem because each thread accesses its own variable, complementary to each other. Similar to everyone who sells their own tickets.

The following changes are for multiple threads selling one ticket:

  

 PackageSoarhu;/*** Created by Huaox on 2017/4/17. **/classThreadTestImplementsrunnable{Private intCount = 5; @Override Public voidrun () { while(count-->0) {Thread.yield ();//give the scheduler the opportunity to execute on other threads. This method is typically used in debugSystem.out.println (Thread.CurrentThread (). GetName () + "count:->" +count); }    }} Public classTest { Public Static voidMain (string[] args) {threadtest thread=Newthreadtest ();  for(inti = 0; I < 3; i++) {            NewThread (thread,i+ ""). Start (); }    }}

Output Result:

0 count:-> 4
2 count:-> 2
1 count:-> 2
2 Count:-> 0
0 count:-> 1

It can be seen that two threads at the same time count of 2, that is, two salespersons sold the ticket, the remaining tickets are the same, which is not allowed, that is, thread insecurity situation. This occurs because, in some cases, i++ is similar to this operation as a non-atomic operation. May be divided into 3 parts. 1: Get the value of I, 2:i+1,3: Assign to I. In these three cases. If more than one thread is accessing it at the same time, a security issue occurs. There are many ways to modify it. For example, it can be avoided by setting it as a synchronization block, or by synchronizing methods, displaying lock objects, and so on. For example:

 PackageSoarhu;/*** Created by Huaox on 2017/4/17. **/classThreadTestextendsthread{Private intCount = 5; @Override Public  voidrun () {synchronized(ThreadTest.class) {            if(count-->0) {//The IF block should be changed here, and if it is while other threads will not be executedThread.yield ();//give the scheduler the opportunity to execute on other threads. This method is typically used in debugSystem.out.println (Thread.CurrentThread (). GetName () + "count:->" +count); }        }    }} Public classTest { Public Static voidMain (string[] args) {threadtest thread=Newthreadtest ();  for(inti = 0; I < 5; i++) {            NewThread (thread,i+ ""). Start (); }    }}

Output Result:

0 count:-> 4
1 count:-> 3
4 Count:-> 2
3 count:-> 1
2 Count:-> 0

Now the result output all normal!

Basic Overview of Java Multithreading

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.