Polls encountered during multithreading and overcome

zhaozj2021-02-16  57

It has been a lot of time in contact with the multi-thread, but also a lot of things, but always feel that it is not so moving, when Debug, it will be more worried about what problems in synchronization, think of "Programmer" Written code "This sentence, I feel that it is not fake. I finally had one day, I think it is time to figure out this question, so I will find relevant content on the Internet, and I can't find this stage. It should be seen, not too simple, just a strike, I don't know the cloud.

Waste the force of Nine Bull, finally, it is almost clear, there are many misunderstandings, which I have thoughtful and truth is very different. I think of my time spent, I really feel a bit more, so write it out, one is to prevent itself In the future, I will forget, the other is to give a point that can be referred to as I like me.

Gossip less, transfer to the topic!

-------------------------------------------------- ------------------------------

First create from the thread. There are two forms of the creation of threads:

-------------------------------------------------- ------------------------------

One is inheriting from the Thread class .hetive class is a specific class, ie not an abstract class, which encapsulates the behavior of threads. To create a thread, the programmer must create a new class exported from the Thread class. The programmer completes useful work by overlying the run () function of Thread. The user does not call this function directly; but by calling the Start () function of Thread (), the function calls Run ().

E.g:

Public class test extends thread {

Public test () {

}

Public static void main (string args []) {

Test T1 = New Test ();

TEST T2 = New Test ();

T1.Start ();

T2.Start ();

}

Public void run () {

// do thread's thing

}

}

-------------------------------------------------- ------------------------------

The other is to implement the runnable interface, this interface has only one function, Run (), this function must be implemented by a class that implements this interface.

E.g:

Public class test implements runnable {

Thread thread1;

Thread thread2;

Public test () {

Thread1 = New Thread (this, "1");

Thread2 = New Thread (this, "2");

}

Public static void main (string args []) {

Test T = New Test ();

T.startThreads ();

}

Public void run () {

// do thread's thing

}

Public void startthreads () {

Thread1.start ();

Thread2.start ();

}

}

The two creation methods are different, the first is because inheritance from THREAD, only its own object is created, the second kind has to create the Thread object. But when you want to inherit a certain class, you can only use the latter way. The reason why most people prefer it is also here.

-------------------------------------------------- ------------------------------

Let's talk about the four uses of Synchronized:

1. When the method declares, after the range operator (public, etc.), return to the type declaration (Void et al.). At this time, the thread is a member lock, that is, only one thread can enter the method, other threads To call this method at this time, you can only queue wait, the current thread (that is, the other threads can enter after the method is executed. For example:

Public synchronized void synmethod () {

// method body

}

2. Use a code block, Synchronized followed by parentheses, parentheses is a variable, so that only one thread enters the code block at a time. At this time, the thread is a member lock. For example:

Public int synmethod (int A1) {

Synchronized (a1) {

// can only have a thread to enter again

}

}

3. Synchronized is an object in the brackets. At this time, the thread is an object lock. For example:

Public class mythread implements runnable {

Public static void main (string args []) {

Mythread MT = new mythread ();

Thread T1 = New Thread (MT, "T1");

Thread T2 = New Thread (MT, "T2");

Thread T3 = New Thread (MT, "T3");

Thread T4 = New Thread (MT, "T4");

Thread T5 = New Thread (MT, "T5");

Thread T6 = New Thread (MT, "T6");

T1.Start ();

T2.Start ();

T3.Start ();

T4.Start ();

T5.Start ();

T6.Start ();

}

Public void run () {

Synchronized (this) {

System.out.println (thread.currentthread (). Getname ());

}

}

}

For 3, if the thread is entered, you get the current object lock, then other threads can not be performed any operation on all objects of the class. The object-level use lock is usually a relatively rough method. Why do you want to lock the entire object without allowing other threads to use other synchronization methods in the object to access shared resources? If an object has multiple resources, it is not necessary to lock all threads outside only to let a thread use some of the resources. Since each object is locked, you can use the virtual object to be locked as follows:

Class FinegrainLock {

Mymemberclass x, y;

Object xlock = new object (), ylock = new object ();

Public void foo () {

Synchronized (xlock) {

// Access X here

}

// Do Something Here - But don't use shared resources

Synchronized (Ylock) {

// Access Y Here

}

}

Public void bar () {

Synchronized (this) {

// Access Both x and y here

}

// Do Something Here - But don't use shared resources

}

}

4. Synchronized is a class in parentheses, at this time, the thread is an object lock. For example:

Class arraywithlockorder {

Private static long num_locks = 0;

PRIVATE long LOCK_ORDER

Private int [] arr; public arraywithlockorder (int [] a)

{

Arr = a;

Synchronized (arraywithlockorder.class) {// ----------------------------------------- Here

Num_locks ; // Lock number plus 1.

Lock_order = num_locks; / / Set the unique Lock_Order for this object instance.

}

}

Public long lockorder ()

{

Return Lock_Order;

}

Public int [] array ()

{

Return ARR;

}

}

Class Someclass Implements Runnable

{

Public Int Sumarrays (ArraywithlockOrder A1,

Arraywithlockorder A2)

{

INT value = 0;

ArraywithLockorder first = a1; // Reserved one of the array references

Arraywithlockorder last = a2; // local copy.

INT size = a1.Array (). Length;

IF (size == a2.Array (). Length)

{

IF (a1.lockorder ()> a2.lockorder ()) // Determines the lock of the object

{// order.

FigSt = a2;

Last = a1;

}

Synchronized (first) {// locked the object in the correct order.

Synchronized (last) {

Int [] arr1 = a1.Array ();

Int [] arr2 = a2.Array ();

For (int i = 0; i

Value = arr1

Arr2;}}} Return Value;} PUBLIC VOID RUN () {// ...}} For 4, if the thread enters, the thread is not performed in this class, including static variables and static methods, actually For synchronization of code blocks containing static methods and static variables, we usually use 4 to lock.

-------------------------------------------------- ------------------------------ Let's talk about some common methods:

Wait (), WAIT (LONG), NOTIFY (), NotifyAll (), etc. is the instance method of the current class.

Wait () is a thread release lock that holds an object lock;

WAIT (long) is a thread release lock time that holds an object lock is long (milliseconds), and then get the lock again, Wait () and Wait (0) equivalent;

Notify () is a thread that wakes up a waiting object lock. If the waiting thread is not only one, the waken thread is determined by the JVM;

NotifyAll is a thread that wakes up all waiting object lock.

Here I also reiterate us, we should use the NotifyAll () method because the wake-up thread is easier to get JVM to find wake-up threads than awakening a thread.

For the above method, only in the current thread can be used, otherwise the runtime error java.lang.illegalMonitorstateException: Current Thread Not Owner.

-------------------------------------------------- -----------------------------, I will talk about Synchronized and Wait (), Notify (), etc.: Producer / Consumer This example is best to explain the relationship between them:

Public class test {public static void main (STRING ARGS []) {semaphore s = new semaphore (1); thread t1 = new thread (s, "produter1"); thread t2 = new thread (s, "produter2"); Thread T3 = New Thread (S, "Producer3"); Thread T4 = New Thread (S, "Consumer1"); Thread T5 = New Thread (S, "Consumer2"); Thread T6 = New Thread (s, "consumer3" ); T1.start (); t2.start (); t3.start (); t4.start (); t5.Start (); t6.start ();}} class semaphore import (}}) Semaphore (int N) {this.count = n;} public synchronized void acquire () {while (count == 0) {TRY {Wait ();} catch (interruptedException e) {// Keep Trying}} count - } Public synchronized void release () {while (count == 10) {Try {Wait () {// Keep Trying}} count ; notifyall (); // alert a thread That's Blocking ON This semaphore} public void Run () {while (THREAD.CURRENTTHREAD (). getName (). Substring (0,8) .EqualsignoreCase ("consumer")) {acquire ();} else if (Thread.currentThread (). GetName (). Substring (0,8) .Equalsignorecase ("product")) {release ();} system.out.println (thread.currentthread (). getName () " count);}}} production Production, consumer consumption, generally there is no conflict, but when the stock is 0, consumers should not consume, but when the stock is the upper limit (here 10), the producer can not be produced. Please study the above procedures. You will make a lot more than before.

The above code illustrates Synchronized and Wait, Notify has no absolute relationship, in the method of synchronized declaration, code block, you can do it without Wait, Notify, etc., however, if threads have some kind of contention In the case, you must put the thread in a wait or wake. The article is finally written. Basically, I have written all my learning income, but I will leave some regrets, such as Synchronized is a deep instructions and discussion. Moreover, the article is limited by its own ability, some places will definitely have errors, I hope to have any suggestions and criticism, please post below, I will fix the article. Thank you!

转载请注明原文地址:https://www.9cbs.com/read-18872.html

New Post(0)