Black Horse Programmer------Multithreading (ii)

Source: Internet
Author: User
Tags thread stop ticket

Black Horse Programmer------Multithreading (ii)

1.1 Synchronizing code blocks: Java provides a professional solution to multithreading security issues

Format:

Synchronized (object)
{
Code that needs to be synchronized (shared data)

}

objects are like locks. The thread holding the lock can be executed in sync.
A thread that does not hold a lock even gets the execution of the CPU, and cannot get in because the lock is not acquired.

The bathroom on the train---classic.

Prerequisites for synchronization:
1, there must be two or more than two threads.
2, the same lock must be used by multiple threads.

You must ensure that only one thread in the synchronization is running.


Benefits: Solves the problem of multithreading security.

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

Example 1:

1 classTicketImplementsRunnable2 {3     Private  intTick = 1000;4Object obj =NewObject ();5      Public voidRun ()6     {7          while(true)8         {9             synchronized(obj)Ten             { One                 if(tick>0) A                 { -                     //Try{thread.sleep (10);} catch (Exception e) {} -System.out.println (Thread.CurrentThread (). GetName () + ".... Sale:" + tick--); the                 } -             } -         } -     } + } -  +  A classTicketDemo2 at { -      Public Static voidMain (string[] args) -     { -  -Ticket T =NewTicket (); -  inThread T1 =NewThread (t); -Thread t2 =NewThread (t); toThread t3 =NewThread (t); +Thread T4 =NewThread (t); - T1.start (); the T2.start (); * T3.start (); $ T4.start ();Panax Notoginseng  -  the     } +}

1.2 Synchronization functions

Synchronization function Format:

Public synchronized void Show ()

{

}

How do I find a problem?

1. Identify which code is multithreaded to run the code

2. Clearly shared data

3. What are the statements in multithreaded run code that manipulate shared data?

The lock for the synchronization function is this. The function needs to be called by the object, so the function has a reference to the owning object.

Want to let the thread stop

Thread.Sleep (10);

If the synchronization function is statically decorated, the lock used is class

Synchronized (object name. Class)

1.3 Dead Lock:

Nested synchronization in synchronization, may occur, how to resolve

is because two threads are waiting for each other to have a locked resource

Cyclic wait condition: The first thread waits for another thread, while the second waits for the first thread.

A common rule of thumb for avoiding deadlocks is that when several threads have access to shared resources A, B, C,

Ensure that each thread accesses them in the same order, for example, by accessing a, and accessing B and C.

1.4 Inter-thread communication: Multiple threads operate on the same resource, but the actions are different.

1. is not two or more than two threads. Workaround two threads are to be synchronized.
2. is not the same lock. Workaround find the same object as the lock.

Wait for the wake mechanism.

After wait, the thread is present in the thread pool, and the threads in the thread pool wake up after notify.
Notifyall (); Wakes all threads in the thread pool.
Implementation method:

Add a flag flag to a resource

Synchronized (R)
{
while (R.flag)//multiple producers and consumers if (R.flag)//a producer and consumer
R.wait ();
Code
R.flag=true;
R.notify ();
R.notifyall ();
}

All three of the above methods are used in synchronization, because the thread holding the monitor (lock) is being manipulated. So to use in synchronization, because only synchronization has a lock.

Why are the methods of these operations threads defined in the object class?
Because these methods are even in the process of synchronizing the threads, they must represent only the locks that they operate on the thread. Only the same locked thread that is being waited on can be
The same locked notify wakes up, and the threads in different locks cannot be awakened.

That is, the wait and wake must be the same lock, and the lock can be a deliberate object that can be defined in the object class by any method called by any object.


1.5 Lock Interface multi-producer and consumer JDK1.5 version upgrade (example 2)
Lock replaces the synchronized
Condition replaces the object monitor method

Benefit: Replace sync synchronized with Lock
Replaces the wait notify Notifyall in object with the condition object
The object can be obtained by lock lock. A lock can correspond to multiple condition objects
Note: The job of releasing the lock must be performed

Example 2

1 PrivateLock lock=NewReentrantlock ();2 PrivateCondition Condition =lock.newcondition ();3 4  Public voidCET (String name)throws 5 {6 Lock.lock ();7    Try8    {9        while(flag)Ten contidition.await (); One         This. name=name+ "--" +count++; A  -SOP (Thread.CurrentThread (). GetName () + "... Producer ... "+ This. Name) -flag=true; the Condition.signalall (); -  -     } -     finally +     { - Lock.unlock (); +           A    } at}

1.6 Stop thread, daemon thread, join method:

To stop a thread:

At the end of the Run method, the thread is stopped, the multithreaded run is turned on, and the running code is usually a looping structure. As long as you control the loop, you can let the thread end.

Method: Change the tag.


In special cases, changing the mark will not stop the situation.

Restores the frozen thread to the running state. Interrupt (); The thread is disconnected.

Daemon Thread:
Setdaemon marks a thread as either a daemon thread or a user thread. Called before the thread is started. The JVM exits when the thread is both a daemon thread.

Join method:

T.join (); Grabbed the CPU execution right.

When a thread executes to the join method of the B thread, a waits until the B thread executes and a executes. Join can be used to temporarily join thread execution.

Priority level:
SetPriority (1-10) Set the priority level.
Thread.max_priority 10
Thread.min_priority 1
Thread.norm_priority 5

Yield method: Pauses the currently executing thread object and executes other threads.

Application in development:: Ensure that the following three code runs simultaneously.


Example 3:

1 NewThread ()2 {3        for(intx=0;x<100;x++)4       {5 SOP (Thread.CurrentThread (). GetName ())6 7        }8 }.start ();9 Ten  One   for(intx=0;x<100;x++) A { - SOP (Thread.CurrentThread (). GetName ()) -  the } -  -Runnable r=NewRunnable () - { +     PublicVoud Run () { -       for(intx=0;x<100;x++) +      { A SOP (Thread.CurrentThread (). GetName ()) at  -      } -  -     } - }; -  in NewThread (R). Start ();

Black Horse Programmer------Multithreading (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.