public class SynchronizedTest implements Runnable{
private static volatile int m=0;
private Object object=new Object();
public static void main(String[] args) {
Runnable run=new SynchronizedTest();
Thread thread1=new Thread(run);
Thread thread2=new Thread(run);
thread1.start();
thread2.start();
try {
//join() 使main线程等待这连个线程执行结束后继续执行下面的代码
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("m的最终结果:"+m);
}
public void run() {
synchronized (object) {
for(int i=0;i<10000;i++){
m++;
}
}
}
}
1、同步方法
package com.linuxidc.base.threadTest;
public class SynchronizedTest implements Runnable{
private static int m=0;
public static void main(String[] args) {
Runnable run=new SynchronizedTest();
Thread thread1=new Thread(run);
Thread thread2=new Thread(run);
thread1.start();
thread2.start();
try {
//join() 使main线程等待这连个线程执行结束后继续执行下面的代码
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("m的最终结果:"+m);
}
public synchronized void run() {
for(int i=0;i<10000;i++){
m++;
}
}
}
这段代码中,synchronzied作用于一个实例方法,就是说当线程在进入run()方法前,必须获取当前对象实例锁,本例中对象实例锁就是run。在这里提醒大家认真看这三段代码中main函数的实现,在这里我们使用Runnable创建两个线程,并且这两个线程都指向同一个Runnable接口实例,这样才能保证两个线程在工作中,使用同一个对象锁,从而保证线程安全。
一种错误的理解:
package com.linuxidc.base.threadTest;
public class SynchronizedTest implements Runnable{
private static int m=0;
public static void main(String[] args) {
Thread thread1=new Thread(new SynchronizedTest());
Thread thread2=new Thread(new SynchronizedTest());
thread1.start();
thread2.start();
try {
//join() 使main线程等待这连个线程执行结束后继续执行下面的代码
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("m的最终结果:"+m);
}
public synchronized void run() {
for(int i=0;i<10000;i++){
m++;
}
}
}