I. Thread SAFETY
A thread safety problem is that something common in a program is accessed by multiple threads, such as a static variable of a class
Two. Sync Lock
Is there any way to solve the problem of thread safety? And that's the lock in the program.
Java has two methods of locking:
1. Lock synchronized (this) {...} in the code block
2. Lock public synchronized void xxx () on the method {...}
Example code:
public class Traditionalthreadsynchronized {public static void main (string[] args) {new traditionalthreadsynchronized () . Init ();} private void Init () {final Outputer outputer = new Outputer ();//thread 1new threads (new Runnable () {@Overridepublic void run () {while (true) {try {Thread.Sleep]; OUTPUTER.OUTPUT1 ("1111111111");} catch (Exception e) {e.printstacktrace ();}}}). Start ();//thread 2new thread (new Runnable () {@Overridepublic void run () {while (true) {try {thread.sleep]; o UTPUTER.OUTPUT1 ("2222222222");} catch (Exception e) {e.printstacktrace ();}}}}). Start ();} Class Outputer {public void output1 (String name) {//Synchronized code block synchronized (this) {for (int i = 0; i < name.length (); i++) {System.out.print (Name.charat (i));} System.out.println ();}} Synchronization method public synchronized void Output2 (String name) {for (int i = 0; i < name.length (); i++) {System.out.print (name.ch Arat (i));} System.out.println ();}}}
Thread 1 and thread 2 because both call the Output1 method and print the incoming name string, the CPU switches back and forth between two threads.
It is possible to switch to thread 2 when thread 1 is printed halfway, which is obviously something we don't want to see, so lock in the code content,
This guarantees that a thread calls the method to end before executing the next thread.
This in the code above refers to the Outputer object, which is a lock, two threads use the same lock to achieve synchronization.
Locking on the method also enables thread synchronization, and using the Synchronized keyword on the method also takes this as a lock.
in fact, OUTPUT1 methods and Output2 methods are also synchronous, because they are all using this as a lock.
Consider a question: if you define a method as static, that is: public static synchronized
So what does it use as a lock? The answer is: The byte-code object of the class Xxx.class
Traditional multi-thread synchronization lock (ii)