Thread safety, synchronization locks (synchronization method and a synchronization code)

1. The security thread (thread-locking Synchronized): processing threads in two ways: 1 sync block synchronization lock 2.
2. The sync block: the lock object may be any object: to set a plurality of threads in the thread when program in order to ensure thread safety lock
3. the synchronization method: this object can be locked, because this represents the meaning of this class, is a kind of the object.
4. set the synchronization lock: synchronization code block: public class Tick implements Runnable () {grab votes compiled program: private int tick; // thread object shared variables to be defined on the class otherwise defined method in which each thread has become variables, such as: each thread has 100 votes and a total of 100 tickets not Object obj = new Object (); thread-locking object class defined otherwise must be placed each thread has a thread lock can not lock the object of
public void run () {while ( true) plus synchronous (synchronized (obj) {{if (tick> 0) { plus make more effective sleep (sleep 100 ms):. Thread.sleep (100) system.out.println (Thread.currentThread () getName ( ) + "sale of" + ticket - + "tickets")}}}
The synchronization methods: public class tick implements R unnable () {int Private the tick = 100; the while (to true) {Save ();}}
. Synchronized public void Save () {IF (the tick> 0) {System.out.println (Thread.currentThread () getName () + "sale of" + ticket - + "tickets");}} \
The lock synchronization method of writing in which Runnable implementation class synchronization lock method and then call on the line
6.Lock multi-threaded lock: private int tick = 0; create lock lock: Lock l = new ReentrantLock () ; cycling tickets: while (true ) {l.lock (); if ( tick> 0) {system.out.println (Thtread.currentThread () .getName () + " on sale" + tick - + "ticket" closed lock} resources: l .unclock}

Guess you like

Origin www.cnblogs.com/hankai2735/p/11481880.html