JAVA multithreading mechanism (ii)

Source: Internet
Author: User
Tags ticket

Main content

1. Understanding the concurrency of threads

2. Synchronization of Threads

3. Common methods of threading

In the previous chapter, because of the concurrency of threads, there are always some problems with multithreaded execution: The concurrency of threads is not controlled by programmers

, and inevitably, the concurrency of threads often leads to problems. So why should we control the concurrency of threads? than

such as: A Childe Management officer is revising the employee's payroll, and some employees are receiving wages, if allowed to do so will inevitably causing

Confusion, so the payroll Manager is revising the payroll, not allowing any employees to pay, which means that employees must perform

Wait state:

 Public classTickets { Public Static voidMain (string[] args) {sel s=Newsel (); Thread T1=NewThread (s); Thread T2=NewThread (s); Thread T3=NewThread (s);         T1.start ();         T2.start ();    T3.start (); }}classSelImplementsrunnable{Private intnum=100;  Public voidrun () { while(true)        {            Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            if(num>0) {System.out.println (Thread.CurrentThread (). GetName ()+ "Selling +num+" Ticket "+num--"); }Else            {                 Break; }        }    }}

is still the issue of ticket sales, the above thread due to the concurrency of the thread caused by the ticket window has a problem.

To solve this problem, we introduce thread synchronization.

2. Synchronization of Threads

What is synchronization: My understanding is that there are three threads above, and when the T1 thread starts to call the run () method, the synchronization function also plays a role when T1 executes the run ()

method, the CPU assigns a key (and only one) to the T1 thread, and then it opens the lock on the synchronized function and then goes inside to execute the method,

At the same time holding the key, and then lock the door, the other threads want to access this function when the CPU does not have the key, the key is thread T1 take in, so the other threads can only be online pool

, when the T1 executes, the door opens, and the key is returned to the CPU, then t1 the thread or dies, or goes into a blocking state, or performs other procedures

The CPU then gives the key back to the thread pool that is queued for waiting, and so on.

(1) Synchronized synchronization function

(2) Synchronized synchronous code block

Synchronization functions:

 Public classTickets { Public Static voidMain (string[] args) {sel s=Newsel (); Thread T1=NewThread (s); Thread T2=NewThread (s); Thread T3=NewThread (s);         T1.start ();         T2.start ();    T3.start (); }}classSelImplementsrunnable{Private intnum=100;  Public synchronized voidRun ()//the establishment of synchronization function    {         while(true)        {            Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            if(num>0) {System.out.println (Thread.CurrentThread (). GetName ()+ "Selling +num+" Ticket "+num--"); }Else            {                 Break; }        }    }}

Then the issue of the above-sold tickets has been resolved, there will not be a ticket to be sold many times, or the possibility of selling the No. 0 ticket.

Synchronizing code blocks:

 Public classTickets { Public Static voidMain (string[] args) {sel s=Newsel (); Thread T1=NewThread (s); Thread T2=NewThread (s); Thread T3=NewThread (s);         T1.start ();         T2.start ();    T3.start (); }}classSelImplementsrunnable{Private intnum=100;  Public  voidRun ()//establishment of synchronous code blocks    {        synchronized( This)        {         while(true)        {            Try{Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            if(num>0) {System.out.println (Thread.CurrentThread (). GetName ()+ "Selling +num+" Ticket "+num--"); }Else            {                 Break; }        }    }    }}

The implementation of the synchronous code block also avoids the concurrency of threads, and the synchronization code block is more advantageous than the synchronous function, which synchronizes the code block's

Efficiency is also higher than the synchronization function. Most importantly, the benefits of synchronizing code blocks are:

The lock for a synchronization function can only be this, and the synchronous code block may be any obj object, and you can define your own class to define your own locks

The speed of the synchronous code block is also faster than the synchronization function, and the application is more extensive. Therefore, when dealing with multithreading security issues

It is best to use synchronous code blocks:

Common methods of threading

1.start () 2.run () 3.sleep () 4.isAlive () 5.currentThread () 6.interrupt ()

The previous three were not introduced. Presumably learned the thread to know what these three methods mean, the IsAlive () method is to judge

Whether the current thread is still alive. The CurrentThread () method is to get the object name of the current thread of execution, and the interrupt () method is to wake

The dormant thread: Here's an example ...

/** For example, Chenyin is sleeping, so it is class time * Zhang Xiao Shuai sleeping thread is executing, but in class * teacher this thread saw a little handsome sleeping thread, and then * directly woke up a small handsome thread ... * */ Public classDemo_1_1 { Public Static voidMain (string[] args) {classroom=NewClassroom ();        Room.students.start ();    Room.teacher.start (); }}classClassroomImplementsrunnable{Thread Students,teacher; Classroom () {teacher=NewThread ( This); Students=NewThread ( This); Teacher.setname ("Miss Zhang"); Students.setname ("Great little"); }     Public voidrun () {if(Thread.CurrentThread () = =students) {System.out.println (Thread.CurrentThread (). GetName ()+ "sleeping, no lectures"); Try{Thread.Sleep (1000*60*60); } Catch(interruptedexception e) {System.out.println (Students.getname ()+ "Awakened"); } System.out.println ("Start Listening"); }        Else if(Thread.CurrentThread () = =teacher) {             for(inti=1;i<=3;i++) {System.out.println (Class); Try{Thread.Sleep (500); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace ();        }} students.interrupt (); }    }}

By the way, a mouth. An already running thread does not assign an entity again when it is not in the dead state, because the thread's allocation can only reference

The last entity, the previous entity becomes garbage, and the garbage collector does not recycle because the JVM thinks that the garbage

The entity is running and if it is suddenly interrupted, it will inevitably cause damage to the device ...

For example:

Thread thread=new thread (target);

Thread.Start ();

If you execute the following statement again ...

Thread=new Thread (target), then the original entity will become garbage ...

Just like the following ....


Therefore, when writing multi-threaded, it is important to avoid such problems occur ...

JAVA multithreading mechanism (ii)

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.