Multithreading series Two: Single Thread execution mode

Source: Internet
Author: User
Tags semaphore

One, what is singlethreadexecution mode?
Only one thread can perform processing at the same time

Two, examples

1. Unsafe conditions

The program simulates three of people frequently passing through a door that only allows one person to pass through. When a person passes, the number of statisticians increases and the name and address of the user are recorded.

Door:

 Public classGate {Private intCounter = 0; PrivateString name = "Nobody"; PrivateString address = "Nowhere";  Public voidPass (string name, address of string) { This. counter++;  This. Name =name;  This. Address =address;    Check (); }     PublicString toString () {return"NO." +counter+ ":" +name+ "," +address; }    Private voidCheck () {if(Name.charat (0)! = Address.charat (0) {System.out.println ("*****borken******" +toString ()); }    }}

Pass by:

 Public classUserthreadextendsthread{Private FinalGate Gate; Private FinalString MyName; Private FinalString myAddress;  PublicUserthread (Gate Gate, String myname,string myAddress) { This. Gate =Gate;  This. MyName =MyName;  This. myAddress =myAddress; } @Override Public voidrun () {System.out.println (MyName+ "are ready ...");
Frequent passage through the door while(true) {gate.pass (myname,myaddress); } }}

Create three people through the door

 Public class Test {    publicstaticvoid  main (string[] args) {        new Gate ();         New Userthread (Gate, "AAA", "AA"). Start ();         New Userthread (Gate, "BBB", "BB"). Start ();         New Userthread (Gate, "CCC", "CC"). Start ();    }}

Operation Result:

CCC is ready ....
BORKEN******NO.4717:AAA, BB
Analysis:

When the person passes through the door, it will record the person's name and the person's address. But from the results of this line, this is not the same as what we expected.

2. Examples of security

The above problem arises at the same time not only one person passes (possibly many people simultaneously through this gate), causes the record person's name and the address to appear the confusion. How to solve it? In fact, we just have to make sure that only one person passes the door at a certain moment, and the problem is solved. We can consider using single Thread execution mode.

Thread-Safe Doors:

 Public classSafegate {Private intCounter = 0; PrivateString name = "Nobody"; PrivateString address = "Nowhere";  Public synchronized voidPass (string name, address of string) { This. counter++;  This. Name =name;  This. Address =address;    Check (); }     Public synchronizedString toString () {return"NO." +counter+ ":" +name+ "," +address; }    Private voidCheck () {if(Name.charat (0)! = Address.charat (0) {System.out.println ("*****borken******" +toString ()); }    }}

The rest does not have to change.

Operation Result:

AAA is ready ....
BBB is ready ....
CCC is ready ....

The role of 3.synchronized
The Synchronized method ensures that the method can be executed by only one thread at a time

Third, the role in the Singlethreadexecution model
SharedResource resources: Classes that can be accessed by multiple threads, including many methods, divided into two categories
Security method: Simultaneous access to multiple threads does not matter
Unsafe method: Multiple thread access issues that must be protected
The singlethreadexecution mode protects unsafe methods so that they can be accessed by only one thread at a time
Critical section: A program scope that allows only a single thread to execute

Four, when to use Singlethreadexecution mode?
1. When multi-threading
2. When multiple threads are accessed: When an instance of the Shareresource role may be accessed concurrently by multiple threads
3. When the state is subject to change: the status of the Shareresource role changes
4. When you need to ensure security:

Five, survivability and deadlock
1. When using singlethreadexecution mode, there is a risk of deadlock
2. A deadlock is a phenomenon in which two threads hold each other and wait for each other to release the lock.
3. Deadlock condition occurs:
There are multiple sharedresource roles
The thread acquires the lock of the other SharedResource role while holding the lock of a sharedresource role
The order of the locks that get the sharedresource role is not fixed

Six, critical zone size and performance
The singlethreadexecution mode degrades performance because:
1. Time taken to acquire locks
When entering the synchronized method, the thread needs to acquire the lock of the object, which takes time. If the number of sharedresource roles is reduced, the number of locks acquired decreases and time is reduced.
2. Wait due to thread conflict
When thread a executes the code for a critical section, threads that other threads want to enter the critical section block, which is called a thread conflict. The probability of thread collisions can be reduced by minimizing the range of critical areas.

Seven, Before/after mode
1.synchronized syntax
Synchronized (this) {
....
}
The above syntax can be thought of as acquiring a lock at {and releasing the lock at the} place.
2. Show processing lock
void Method () {
Lock ();//Locking
...
Unlock ();//unlock
}

Cons: If there is a return between the lock method and the Unlock method, the lock cannot be freed. When an exception is thrown between lock and unlock, the lock cannot be freed. and synchronized whether it's return
or throws an exception, it must be able to release the lock.
3. Resolution:
We want to call lock (), no matter what we do, unlock () will be called, we can use finally to handle
void Method () {
Lock ();
try{
...
}finally{
Unlock ();
}
}

Finally, this usage is one of the implementation methods of the Before/after mode (pre/post mode).

Eight, thinking
Thinking when using synchronized:
What is synchronized protecting?
Is the rest of the place properly protected?
In what unit of protection
Which lock is used to protect
2. Atomic operation
From a multithreaded point of view, the operation performed by this synchronized method is an indivisible operation that can be seen as an atomic operation

Nine, count Semaphore and Semaphore class

The single thread execution mode is used to ensure that a zone can only be executed by one thread. How do we do this if we want to have a zone that can be executed by up to n threads?

The Java.util.concurrent package provides a semaphore class that represents the semaphore of the count. can be used to control the number of concurrent

The acquire method of the semaphore class is used to ensure that available resources exist

The release method of the semaphore class is used to release resources.

 Public classSemaphoretest { Public Static voidMain (string[] args) {Executorservice Executorservice=Executors.newcachedthreadpool (); FinalSemaphore SP =NewSemaphore (3);  for(inti = 0; I < 10; i++) {Runnable Runnable=NewRunnable () {@Override Public voidrun () {Try {                        //take the signal .Sp.acquire (); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println ("Thread" +thread.currentthread (). GetName () + "Enter, current already" + (3-sp.availablepermits ()) + "concurrency"); Try{Thread.Sleep (Long) (Math.random () *10000)); } Catch(interruptedexception e) {e.printstacktrace (); }                    //Processing Business                    Try{System.out.println ("Handling Business ..."); }finally{System.out.println ("Thread" +thread.currentthread (). GetName () + "About to leave"); //Release Beaconsp.release (); } System.out.println ("Thread" +thread.currentthread (). GetName () + "left, current" + (3-sp.availablepermits () + "concurrency"));            }            };        Executorservice.execute (runnable); }    }}
When Semaphore sp = new Semaphore (1);  When there is only one signal, the function is equivalent to synchronized  
 code between Sp.acquire and Sp.release allows up to N threads to access simultaneously    

Multithreading series Two: Single Thread execution mode

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.