-
Mutually exclusive access and synchronous access
Complete episode 4-4 (mutually exclusive access) with 4-5 (synchronous access)
1.1 In addition to using the synchronized modification method to achieve mutually exclusive synchronous access, what is the way to achieve mutually exclusive synchronous access (please show the relevant code)? For:
使用Lock方法和Condition对象:
Import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.ReentrantLock;ClassAccount {Privateint balance;Private LockLock =New Reentrantlock ();Private Condition plus =Lock.newcondition ();PublicAccount (int balance) {super ();This.balance = balance; }PublicIntGetBalance () {Synchronizedreturn balance; }PublicvoidDepositint money) {SynchronizedLock.Lock ();try {This.balance=getbalance () +money; Plus.signalall (); }finally {lock.unlock ();}} public void withdraw (int money) {//synchronized lock. Lock (); try {while (GetBalance () <= 0) { try{plus.await ();} catch (interruptedexception e) {e.printstacktrace ();}} this.balance=getbalance ()-money; Plus.signalall ();} finally {lock.unlock ();}}}
1.2 What is the difference between a synchronous code block and a synchronization method? For:synchronization method directly before the method with the synchronized keyword, synchronous code block inside the method to add a lock, the synchronization block needs to indicate the lock object, and the synchronization method by default lock this , synchronous method can only one thread at a time, other threads wait. In terms of performance considerations, it is best to use synchronous blocks to reduce the locking range and increase concurrency efficiency.
1.3 What is the principle of implementing mutually exclusive access? Use the object lock concept and describe it in conjunction with the corresponding code block. How does the state of the thread change when the program executes the synchronized synchronous code block or synchronous method? For
当资源被访问,上锁,但在同一时刻,只能有一个线程获得某个资源的锁,访问该资源,其他线程无法访问。当停止访问时,解锁,让其他线程访问。
class Counter { private static int id = 0; public synchronized static void addId() { id++; } public static int getId() { return id; }
Assuming that there are now two threads t1,t2 and executing this method, when the program executes the synchronized tagged synchronization method, the following steps are taken:1. Thread T1 getid lock, read id value for 0; (thread t2 wait) 2. Thread T1 on the value taken to add 1, the result is 1; 3. Thread T1 results id=1 Save back id,id the lock is unlocked by the resource release; 4. Thread T2 Get id on the lock, read id value, for 1; 5. Thread T2 Add 1 on the value taken, resulting in 2; 6. Thread T1 results id=2 Save back id , the lock of the id is unlocked by the release of the resource, id result 2.
1.4 What keywords are used in Java Multi-threading to implement communication between threads, so that threads work together? Why does synchronous access generally have to be put into synchronized methods or blocks of code? A:Java multi-threading uses the Wait () and notify ()/notifyall () methods to communicate between threads, or to use condition objects. Synchronous access is placed in the Synchronized method or code block to prevent conflicts caused by multiple threads accessing the same resource.
-
Alternating execution
To achieve alternate access, the method is first decorated with synchronized to ensure that all variables hold locks. Second, the collaboration between threads can be done using wait () and notify () and with the Boolean variable, which is called flag if the intermediate bridge is required to perform the task alternately.
-
Mutually exclusive access
3.1 Modify the Testunsynchronizedthread.java source code so that it can be accessed synchronously. (Key code, need to appear number)
3.2 Further use of the actuator to improve the corresponding code (key code, need to appear number)
Reference: Java multi-thread executor, Executorservice, executors, callable, future and Futuretask
-
Collaboration between threads: Producer Consumer issues
4.1 run Myproducerconsumertest.java. The result of the normal operation should be 0 goods left in the warehouse. Run multiple times, observe the results, and answer: Is the result normal? What's not normal? Why? , &NB Sp A: The result is not normal, the remaining number is from 0 to 10, because the producer and the consumer's access speed is inconsistent, So it leads to inconsistent production and consumption. In other words, there is no communication between the threads of the keyword, so there is no cooperation between the threads, it will create confusion. , &NB Sp
4.2 Use synchronized, wait, notify to resolve the issue (key code, number required)
-
Query data answer: What is thread safety? (Use your own words and code to summarize, write your own understanding of the work) A: Thread safety means that multithreaded access to the same code does not produce indeterminate results. If the result of each run is the same as the results of a single-threaded run, and the values of the other variables are the same as expected, it is thread-safe, that is, thread synchronization.
For example
public synchronized static void addId() { id++;}public synchronized static void subtractId() { id--;}
Multiple threads run the above code at the same time, the synchronized keyword causes the thread to synchronize, the results of multiple threads running are consistent with the results of a single thread, both 0,
3. Code submission record on code cloud