synchronize同步问题对于锁得理解
package test.synchronize;
public class AmSynchornizeClass {
private int index=0;
private static int staticIndex = 0;
//成员锁对象
private Object lock = new Object();
/**
* 锁对象是this
* @return
*/
public synchronized int getIndex() {
return index;
}
/**
* 锁对象this 等同于 public synchronized int getIndex(){...}
*/
public int getIndex2() {
synchronized (this) {
return index;
}
}
/**
* 锁对象时成员变量lock
* @return
*/
public int getIndex3() {
synchronized (lock) {
return index;
}
}
/**
* 错误案例:锁对象new Object()离开了方法getIndex4()块没有实际意义
* @return
*/
public int getIndex4(){
synchronized(new Object()){
return index;
}
}
public synchronized void increaseIndex() {
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
index++;
}
public void increaseIndex2() {
synchronized(this){
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
index++;
}
}
public void increaseIndex3() {
synchronized(lock){
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
index++;
}
}
/**
* 锁对象是AmSynchornizeClass.class等同于public static void substract2()
*/
public synchronized static void substract(){
staticIndex--;
}
public static void substract2(){
synchronized(AmSynchornizeClass.class){
staticIndex--;
}
}
}
package test.synchronize;
import org.junit.Test;
public class TestSynchronize {
@Test
public void testSynchronizedLock1() {
final AmSynchornizeClass asc1 = new AmSynchornizeClass();
final AmSynchornizeClass asc2 = new AmSynchornizeClass();
Runnable getThread = new Runnable(){
@Override
public void run() {
System.out.println("go into get method()...");
System.out.println(asc1.getIndex());
System.out.println("get out from get method()...");
}
};
Runnable increaseThread = new Runnable(){
@Override
public void run() {
System.out.println("go into increase method()...");
asc2.increaseIndex();
System.out.println("go out increase method()...");
}
};
Thread t1= new Thread(increaseThread);
Thread t2= new Thread(getThread);
t1.start();
t2.start();
try {
while(true){
if(t1.isAlive() || t2.isAlive()){
Thread.sleep(200);
} else {
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void testSynchronizeLock() {
final AmSynchornizeClass asc = new AmSynchornizeClass();
Runnable getThread = new Runnable(){
@Override
public void run() {
System.out.println("go into get method()...");
System.out.println(asc.getIndex());
System.out.println("get out from get method()...");
}
};
Runnable increaseThread = new Runnable(){
@Override
public void run() {
System.out.println("go into increase method()...");
asc.increaseIndex();
System.out.println("go out increase method()...");
}
};
Thread t1= new Thread(increaseThread);
Thread t2= new Thread(getThread);
t1.start();
t2.start();
try {
while(true){
if(t1.isAlive() || t2.isAlive()){
Thread.sleep(200);
} else {
break;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}