Synchronization lock of traditional multithreading (2)
I. Thread Security
Thread security issues refer to the fact that common things in a program are accessed by multiple threads, such as static variables of classes.
Ii. Synchronization lock
Is there any way to solve the thread security problem? That is, locking in the program.
Java has two locking methods:
1. Lock synchronized (this) {...} in the code block ){...}
2. Lock public synchronized void xxx () {...} on the method (){...}
Sample Code:
Public class TraditionalThreadSynchronized {public static void main (String [] args) {new TraditionalThreadSynchronized (). init ();} private void init () {final Outputer outputer = new Outputer (); // Thread 1new Thread (new Runnable () {@ Overridepublic void run () {while (true) {try {Thread. sleep (10); outputer. output1 ("1111111111");} catch (Exception e) {e. printStackTrace ();}}}}). start (); // Thread 2new Thread (new Runnable () {@ Overridepublic void run () {while (true) {try {Thread. sleep (10); outputer. output1 ("2222222222");} catch (Exception e) {e. printStackTrace ();}}}}). start ();} class Outputer {public void output1 (String name) {// Synchronous Code block synchronized (this) {for (int I = 0; I <name. length (); I ++) {System. out. print (name. charAt (I);} System. out. println () ;}// synchronous method public synchronized void output2 (String name) {for (int I = 0; I <name. length (); I ++) {System. out. print (name. charAt (I);} System. out. println ();}}}
Because both thread 1 and thread 2 need to call the output1 method and print the input name string, the cpu will switch back and forth between the two threads,
It is possible that thread 1 will be switched to thread 2 when it is printed in half. This is obviously not expected, so lock the code content,
This ensures that the next thread is executed only after a thread calls a method.
In the above Code, this refers to the outputer object, which is a lock. Two threads can use the same lock to synchronize data.
The locking method can also implement thread synchronization. the synchronized keyword in the method also uses this as the lock.
In fact, the output1 and output2 methods are also synchronized, because they both use this as the lock.
Think about one problem: if a method is defined as static: public static synchronized
So what does it use as a lock? The answer is: this class's bytecode object xxx. class