synchronized的操作如https://blog.youkuaiyun.com/zjy15203167987/article/details/82531772
1、public class SyncTest implements Runnable{
static int i = 0;
public synchronized void increase(){
//System.out.println(i);
i++;
}
@Override
public void run() {
for(int j=0;j<10000;j++){
increase();
}
}
public static void main(String[] args) throws InterruptedException {
SyncTest syncTest = new SyncTest();
Thread thread1 = new Thread(syncTest);
Thread thread2 = new Thread(syncTest);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(i);
}
}
2、public class SyncTest2 {
public synchronized void method1(){
System.out.println(“method1 start”);
try {
System.out.println(“method1 execute”);
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(“method1 end”);
}
public synchronized void method2(){
System.out.println("method2 start");
try {
System.out.println("method2 execute");
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("method2 end");
}
public static void main(String[] args) {
SyncTest2 test = new SyncTest2();
new Thread(new Runnable() {
@Override
public void run() {
test.method1();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
test.method2();
}
}).start();
}
}