Why take the thread to the beginning? Because the thread is too important, do not say how important the work, just and money directly linked to the development engineer interview will be the problem, if the interview did not ask the relevant questions, or the candidate too much food interview officer too lazy to ask, or the company is too vegetable, do not care about multi-threaded problems.
One, thread safety issues
This class is thread-safe when multiple threads have access to a class and the class behaves correctly.
Synchronized can be added to arbitrary objects and methods to lock, lock the code becomes a mutex or a critical section
Here's a small example of thread safety, and the key is on the word synchronized.
1 ImportJava.util.concurrent.atomic.AtomicInteger;2 3 /**4 * Thread Safety concept: This class (object or method) is thread-safe when multiple threads are accessing a class (object or method), and the object always behaves correctly. 5 * Synchronized: can be locked on any object and method, and the lock code is called "Mutex" or "critical section"6 * @authorAlienware7 *8 */9 Public classMyThreadextendsthread{Ten One Private intCount = 5 ; A - //Synchronized Locking - Public voidrun () { thecount--; -System.out.println ( This. CurrentThread (). GetName () + "Count =" +count); - } - + Public Static voidMain (string[] args) { - /** + * Analysis: When multiple threads access the Mythread run method, they are processed in a queued manner (where the row pairs are based on the sequencing of the CPU allocations), A * A thread that wants to execute the code in the synchronized adornment method: at * 1 Try to get the lock - * 2 If you get the lock, execute the synchronized code body content; If you can't get the lock, the thread will keep trying to get the lock until it gets there . - * And it is multiple threads competing for this lock at the same time. (That is, there will be a lock competition problem) - */ -MyThread MyThread =NewMyThread (); -Thread T1 =NewThread (MyThread, "T1"); inThread t2 =NewThread (MyThread, "T2"); -Thread t3 =NewThread (MyThread, "T3"); toThread T4 =NewThread (MyThread, "T4"); +Thread T5 =NewThread (MyThread, "T5"); - T1.start (); the T2.start (); * T3.start (); $ T4.start ();Panax Notoginseng T5.start (); - } the}
Two, multiple lines multithreading lock
Multiple threads, each thread can get its own designated lock, get the lock and execute the content of the Synchronized method body.
Take a look at the sample code below, what do you think the printed result would be like? Do you think that's the way it should be?
(Expected execution result)
1 /**2 * The lock acquired by the keyword synchronized is an object lock, not a piece of code (method) as a lock,3 * So which thread in the code executes the method of the Synchronized keyword first, which thread holds the lock (lock) of the object to which the method belongs ,4 * 5 * Add synchronized keyword on static method to indicate lock. Class class, Class-level lock (exclusive. Class). 6 * @authorAlienware7 *8 */9 Public classmultithread {Ten One Private intnum = 0; A - /**Static*/ - Public synchronized voidprintnum (String tag) { the Try { - - if(Tag.equals ("a")){ -num = 100; +System.out.println ("tag A, set num over!"); -Thread.Sleep (1000); +}Else { Anum = 200; atSystem.out.println ("tag b, set num over!"); - } - -System.out.println ("tag" + tag + ", num =" +num); - -}Catch(interruptedexception e) { in e.printstacktrace (); - } to } + - //Watch out for the Run method output order the Public Static voidMain (string[] args) { * $ //Two different objects.Panax Notoginseng FinalMultithread M1 =Newmultithread (); - Finalmultithread m2 =Newmultithread (); the +Thread T1 =NewThread (NewRunnable () { A @Override the Public voidrun () { +M1.printnum ("a"); - } $ }); $ -Thread t2 =NewThread (NewRunnable () { - @Override the Public voidrun () { -M2.printnum ("B");Wuyi } the }); - Wu T1.start (); - T2.start (); About $ } - - - A +}
But it's actually like this.
(actual result)
Why does it come to this end? That's because M1 and M2 are two objects, and T1 and T2 each get a lock of two objects, M1 and M2, so the execution of these two threads is irrelevant.
What if I want to get the results I expected? Using class-level locks instead of object locks, the implementation method is to require the static keyword in addition to adding synchronized.
Three, synchronous and asynchronous
Directly on the code:
1 /**2 * Synchronization and asynchronous issues with object locks3 * @authorAlienware4 *5 */6 Public classMyObject {7 8 Public synchronized voidmethod1 () {9 Try {Ten System.out.println (Thread.CurrentThread (). GetName ()); OneThread.Sleep (4000); A}Catch(interruptedexception e) { - e.printstacktrace (); - } the } - - /**synchronized*/ - Public voidmethod2 () { + System.out.println (Thread.CurrentThread (). GetName ()); - } + A Public Static voidMain (string[] args) { at - FinalMyObject mo =NewMyObject (); - - /** - * Analysis: - * T1 thread first holds lock lock for object, T2 thread can invoke non-synchronized decorated method in object asynchronously in * The T1 thread first holds the lock lock for the object, and the T2 thread waits if the synchronization (synchronized) method in the object is called at this time, that is, the synchronization - */ toThread T1 =NewThread (NewRunnable () { + @Override - Public voidrun () { the mo.method1 (); * } $}, "T1");Panax Notoginseng -Thread t2 =NewThread (NewRunnable () { the @Override + Public voidrun () { A mo.method2 (); the } +}, "T2"); - $ T1.start (); $ T2.start (); - - } the -}
If METHOD2 also adds the Synchronized keyword, then the string "T2" will print out after the "T1" string is printed for 4 seconds, when we say method1 and method2 are synchronous.
If METHOD2 removes the Synchronized keyword, then the "T1" string and the "t2" string are printed almost simultaneously, and we say Method1 and METHOD2 are asynchronous.
The reason for synchronization is that the locking after two threads only mo this one object lock.
The architect builds a mind-thread foundation