Detailed Java Basics-Multithreading

Source: Internet
Author: User

------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------

  

If it's easier to do one thing at a time, but in fact a lot of things are done at the same time, Java has introduced threading mechanisms to emulate this state.

When the program completes multiple things at the same time, it is called multithreaded programs.

at one moment, single-core CPU can only run one program. And we see the simultaneous running effect, just CPU is a fast random toggle action between multiple processes.

So multithreading solves the problem of multiple parts running at the same time, but too many threads will certainly affect efficiency.

> First, let's take a picture to show what we're going to do here:

first, the way of realization

The way to implement threading a total of two---inherit the thread class and implement the Runnable interface.

1, inherit the thread class.

A, define class inheritance thread.

B, the Run method in the replication thread.

c. Create an instance object that defines the class.

D. Call the Start method to start the thread.

classTestthreadextendsThread//A, define class inheritance thread. {     Public voidRun ()//B, the Run method in the replication thread.     {         for(intx = 0; x < n × x + +) {System.out.println (Thread.CurrentThread (). GetName ()+"......"+x); }    }}classdemo{ Public Static voidMain (string[] args) {testthread T1=NewTestthread ();//c. Create an instance object that defines the class. Testthread t2=NewTestthread ();                    T1.start (); //d. Call the Start method to start the thread. T2.start (); }}   

2. Implement Runnable interface

A, the definition class implements the Runnable interface.

B. Overwrite the Run method in the Runnable interface.

c. Create thread objects through the thread class.

D. Call the Start method to start the thread.

Class Testthread implements Runnable//a, defines classes to implement Runnable interfaces. {public void Run ()//b, overwriting the Run method in the Runnable interface. {for (int x = 0; x <, + +) {System.out.println (Thread.CurrentThread () + "++++++" +x);}}} Class Demo{public static void Main (string[] args) {Testthread d = new Testthread (); thread T1 = new Thread (d); Thread t2 = new Thread (d);//c, threading object is created through the thread class.     T1.start (); D. Call the Start method to start the thread. T2.start ();}}

3. Realize the advantages of runnable interface

In actual development, we often use the second way to do long threads, and its advantage lies in

A. Avoid encapsulating tasks into objects according to object-oriented thinking.

b, to avoid the limitations of Java single inheritance.

second, the life cycle of the thread

A thread has a life cycle, and its various life cycle relationships are as follows.

third, thread safety

The actual development, the use of multi-threaded situation there are many, such as the train station ticketing system, when there are multiple threads to take the ticket action, assuming that there is only one ticket, the first-line will be sold tickets, at this time the second process to complete the judgment whether there is a ticket action, and the number of votes more than 0 conclusion. A negative number is generated when the ticket is executed.

1, the cause of security problems

A, multiple threads are manipulating shared data

b, there are several codes for manipulating shared data.

2, the solution--synchronization

Encapsulates the thread code for multiple operations that share data, and other threads are not allowed to participate when thread threads execute the code.

A, synchronous code block

  

synchronized (obj) {
Code that needs to be synchronized}

B, synchronization function

 Public synchronized void Show ()  {          //code that needs to be synchronized }     

3. The difference between synchronous function and synchronous code block

The lock for the synchronization function is this

The lock of the synchronization code block is arbitrary (or this can be)

Synchronous code blocks are recommended for practical development.

4, the advantages and disadvantages of synchronization

Benefits: Solves the problem of multithreading security.

Cons: Multiple threads need to determine the lock and consume more resources.

5. Static function code block

If the synchronization function is statically decorated, what is the lock used? The singleton pattern in design mode is shown to everyone.

//Lazy Typeclasssingle{Private StaticSingle S =NULL; PrivateSingle () {} Public StaticSingle getinstance () {if(s = =NULL)        {            synchronized(Single.class)//The static method writes---class name.            {                if(s==NULL) s=NewSingle (); }        }        returns; }}

iv. communication between Threads

The communication between threads is actually that multiple threads share the same resource.

classresorcedemo{ Public Static voidMain (string[] args) {Resorce R=NewResorce (); Input in=NewInput (R); Output out=NewOutput (R); Thread T1=NewThread (in); Thread T2=NewThread (out);        T1.start ();    T2.start (); }}classResorce//Define a resource{String name;    String sex; BooleanFlag =false;}classInputImplementsRunnable//Write Resources{Resorce R; Input (Resorce r) { This. R =R; }     Public voidRun ()//Replication Run Method    {        intx = 0;//x is equivalent to a flag.         while(true)        {            synchronized(r) {if(R.flag = =true)                {                    Try{r.wait (); }                    Catch(Interruptedexception e) {}} Else                {                    if(x==0) {R.name= "Mike"; R.sex= "Nan"; }                    Else{r.name= "Silly girl"; R.sex= "Niu Niu I niu II Niu"; } R.flag=true; R.notify ();//Wake up} x= (x+1)%2;//x is alternating with each other between 0 and 1.                                                            }            }    }}classOutputImplementsRunnable//Read Resources{Resorce R; Output (Resorce r) { This. R =R; }     Public voidrun () { while(true)//Infinite Loops        {            synchronized(r) {if(R.flag = =false)                {                    Try{r.wait (); }                    Catch(Interruptedexception e) {}} Else{System.out.println (r.name+ "..."+r.sex); R.flag=false;                R.notify (); }                            }                    }    }}

v. Common methods of Operation

1,wait (): The thread is frozen and the wait thread is stored in the thread pool.
2,notify (): Wakes a thread in the thread pool (any).
3,notifyall (): Wakes all threads in the thread pool.
4,setpriority (): Set priority
5,yield (): Pauses the current thread for other threads to execute.

Of course, these common operating methods can be found in the API, this is not my point to say, the following to compare these methods.

(1) Wait and sleep difference?

1,wait can specify time or not. Sleep must specify a time.

2, in the synchronization, the CPU execution and lock processing is different.  Wait: Release the execution and release the lock. Sleep: Releases the execution and does not release the lock.

(2) Wait (), notify (), Notifyall (), to manipulate the thread why is it defined in the object class?

A, these methods exist and are synchronized.

B, these methods must be used to identify the synchronized locks that belong to. The same thread that locks wait can only be awakened by the notify of the same lock.

C, a lock can be any object, so the method called by any object must be defined in the object class.

Vi. Summary

Multithreading itself is a relatively complex problem, to fully understand it also takes time, the so-called who can be born skillfully, these knowledge or more to see more practice to practise more to really master.

Detailed Java Basics-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.