1, Synchronized
You will often encounter synchronization problems in your learning threads, and often used is synchronized this keyword, you can understand him as a lock, you can also see the modified method as atomic, that is, this method must be executed in execution, the middle can not be carried out by other threads.
2. Question: When a class has two methods M1 (), M2 ()
(1) M1 with synchronized modification m2 not, when I visit the M1 method can be in the Access M2.
(2) If both of them are decorated with synchronized, can I visit M2 when I visit the M1 method?
3, the code is as follows
(1)
Package com.smart.framework.thread;
/**
* Created with IntelliJ idea.
* Description: * * Public
class TT implements Runnable {
@Override public
void Run () {
m1 ();
} Public
synchronized void M1 () {
try {
thread.sleep (10000);
} catch (Exception e) {
e.printstacktrace ();
}
SYSTEM.OUT.PRINTLN ("M1--->");
}
public void m2 () {
System.out.println ("M2--->");
public static void Main (String args[]) {
TT tt=new TT ();
Thread thread=new thread (TT);
Thread.Start ();
try {
thread.sleep;
} catch (Exception e) {
e.printstacktrace ();
}
TT.M2 ();
}
The results are as follows:
To explain, the above call to the Sleep method is not necessary, just to stagger the time to verify, to enlarge the effect.
You can see that when access is locked, the method that does not affect access is not locked.
(2)
Package com.smart.framework.thread;
/**
* Created with IntelliJ idea.
* Description: * * Public
class TT implements Runnable {
@Override public
void Run () {
m1 ();
} Public
synchronized void M1 () {
try {
thread.sleep (10000);
} catch (Exception e) {
e.printstacktrace ();
}
SYSTEM.OUT.PRINTLN ("M1--->");
}
Public synchronized void m2 () {
System.out.println ("M2--->");
public static void Main (String args[]) {
TT tt=new TT ();
Thread thread=new thread (TT);
Thread.Start ();
try {
thread.sleep;
} catch (Exception e) {
e.printstacktrace ();
}
TT.M2 ();
}
The results are as follows:
You will find that the M2 runs after M1, which means that the execution of the M1 is performed before the execution of M2 is performed, that is, the other M1 modified method of the object cannot be invoked during synchronized execution, and must wait for its end to execute.