Java programming ideas - Chapter 21 concurrent (b)

Third, the sharing of limited resources

  For concurrent tasks, you need some way to prevent two tasks access the same resource, at least not this occurs at a critical stage.

1. solve shared resource contention

  Way to prevent this conflict is that when resources are using a task lock on it. Basically all thread concurrency model in solving conflict, and are based on the sequence of program access shared resources. Usually this statement is to pick the lock achieved by adding the code in front, which makes only one task can run this code at a time. Because the lock statement had the effect of one kind mutually exclusive, so this mechanism to support field becomes mutex (mutex).

  synchronized, when the code to be executed is synchronized when the protected code block, first checks whether the lock is available, then the lock is obtained, the execution code block, releasing the lock. Memory segment shared resource typically is present in the form of an object may be a file, I / O, printers and the like. To control access to shared resources, the need to put it into a package object. Then all calls to this resource method is marked as synchronized. If a task calling for the labeling synchronized method, so so in this thread from before the method returns, all other calls to any class marked as synchronized method threads are blocked.

  All objects, containing a single lock automatically, when calling any of its synchronized method on an object, the object is locked, then the other on the object synchronized after only method until it has finished before a method call and releases the lock in order to be transfer. Note that when using concurrent, set the domain to private is very important, otherwise, the synchronized keyword can not prevent other tasks directly access the domain.

  For each class, also has a lock. Therefore synchronized static methods can be prevented in the range of class static concurrent access to data.

  

  

  

Guess you like

Origin www.cnblogs.com/xcgShare/p/11770688.html