在并发编程中存在线程安全问题,主要原因有:1.存在共享数据 2.多线程共同操作共享数据。关键字synchronized可以保证在同一时刻,只有一个线程可以执行某个方法或某个代码块。
Java中每一个对象都可以作为锁,这是synchronized实现同步的基础。
同步方法块:锁是括号里面的对象或类,对给定对象加锁,进入同步代码库前要获得给定对象的锁。
普通同步方法:锁是当前实例对象 ,进入同步代码前要获得当前实例的锁。
静态同步方法:锁是当前类的class对象 ,进入同步代码前要获得当前类对象的锁。
下面请看详细内容
1 同步代码块
对象锁
为什么要同步代码块呢?在某些情况下,我们编写的方法体可能比较大,同时存在一些比较耗时的操作,而需要同步的代码又只有一小部分,如果直接对整个方法进行同步操作,可能会得不偿失。此时我们可以使用同步代码块的方式对需要同步的代码进行包裹,这样就无需对整个方法进行同步操作了。
public class synchronizedTest implements Runnable {
static synchronizedTest instance = new synchronizedTest();
static int i=0;
@Override
public void run() {
//省略其他耗时操作....
//使用同步代码块对变量i进行同步操作,锁对象为instance
synchronized(instance){
for(int j=0;j<10000;j++){
i++;
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1=new Thread(instance);
Thread t2=new Thread(instance);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
}
输出结果
分析:将synchronized作用于一个给定的实例对象instance,即当前实例对象就是锁对象,每次当线程进入synchronized包裹的代码块时就会要求当前线程持有instance实例对象锁,如果当前有其他线程正持有该对象锁,那么新到的线程就必须等待,这样也就保证了每次只有一个线程执行i++;操作。
当然除了instance作为对象外,我们还可以使用this对象(代表当前实例)或者当前类的class对象作为锁。注意对象锁不一定可以达到同步,要根据具体问题分析是否使用类锁。请看下一节
类锁
类锁定义
对象锁不能实现同一Class的不同对象的线程同步。请看下面这个问题:
例子中共享资源是 static i,两个线程的锁分别是不同的Integer实例。
public class SynchronizedTest3 implements Runnable {
private Integer myLock = new Integer(10);
static int i = 0;
@Override
public void run() {
synchronized (myLock) {
for (int j = 0; j < 10000; j++) {
i++;
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new SynchronizedTest3());
Thread t2 = new Thread(new SynchronizedTest3());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
}
从输出结果看到线程1在执行run()的时候,线程2仍可以执行run()。因为线程2可能拿到老的i,导致最终结果不是20000,表明两个线程没有同步执行。
synchronized加锁时用类锁可以解决上面同步问题,如下是一个类锁
//this,当前实例对象锁
synchronized(this){
for(int j=0;j<1000000;j++){
i++;
}
}
//class对象锁
synchronized(AccountingSync.class){
for(int j=0;j<1000000;j++){
i++;
}
}
类锁
上一节中我们看到对象锁无法解决多个对象的同步问题。使用类锁可以解决多个对象的同步问题。
public class SynchronizedTest3 implements Runnable {
static int i = 0;
@Override
public void run() {
synchronized (SynchronizedTest3.class) {
for (int j = 0; j < 10000; j++) {
i++;
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new SynchronizedTest3());
Thread t2 = new Thread(new SynchronizedTest3());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
}
此时输出结果是20000,表明两个线程是同步操作共享资源的。
静态变量作锁
也可以在用作锁的对象前加static来解决上面的同步问题。
public class SynchronizedTest3 implements Runnable {
private static Integer myLock = 128;
static int i = 0;
@Override
public void run() {
synchronized (myLock) {
for (int j = 0; j < 10000; j++) {
i++;
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new SynchronizedTest3());
Thread t2 = new Thread(new SynchronizedTest3());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
}
输出
因为静态变量本身还是从属于类,所以用静态变量作锁,其实和用类作锁效果一样。
同步整个方法体
有时可能整个方法体都需要用对象本身同步,并且这种情况时很常见的
public void method() {
synchronized(this){
System.out.println("Method 1 start");
try {
System.out.println("Method 1 execute");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method 1 end");
}
}
java对上述同步情况提供了一个快捷方式,可以通过向方法声明添加synchronized,对当前对象同步整个方法,这就是下文要详细讨论的同步方法
public synchronized void method() {
System.out.println(“Method 1 start”);
try {
System.out.println(“Method 1 execute”);
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(“Method 1 end”);
}
2同步方法
普通同步方法
多个线程访问同一对象的同一同步方法
我们以多个线程访问同一个对象的同一个同步方法来验证。
此时锁是实例对象。共享资源是i
public class SynchronizedTest implements Runnable{
//使用静态变量定义共享资源
static int i =0;
/**
* synchronized 修饰实例方法
*/
public synchronized void increase(){
i++;
}
@Override
public void run(){
for (int j =0 ; j<10000;j++){
increase();
}
}
public static void main(String[] args) throws InterruptedException {
SynchronizedTest test = new SynchronizedTest();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
}
这里必须调用join()方法才能看到正确的结果,即输出 20000。如果不加t1.join()方法,主线程main在将线程t1 t2加入到可运行池之后,即线程变为可运行状态,会不等t1.run()执行完毕,直接就会执行System.out.println(i); 输出 0。
t.join()方法会使主线程进入等待池,并等待 t1 t2 线程执行完毕后,才会被唤醒。join() 并不影响同一时刻处在运行状态的其他线程。
多个线程访问同一对象的不同同步方法
此时两个线程的锁都是SynchronizedTest2的实例test
public class SynchronizedTest2 {
public synchronized void method1() {
System.out.println("Method 1 start");
try {
System.out.println("Method 1 execute");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method 1 end");
}
public synchronized void method2() {
System.out.println("Method 2 start");
try {
System.out.println("Method 2 execute");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method 2 end");
}
public static void main(String[] args) {
final SynchronizedTest2 test = new SynchronizedTest2();
new Thread(test::method1).start();
new Thread(test::method2).start();
}
}
从结果看到在线程1执行的时候,线程2是无法获得对象锁的。这表明一个线程获得对象锁时,其它线程只能阻塞,等待锁的释放。
其他线程访问同一对象的非同步方法
但是在对象没有被释放前,其他线程可以访问非synchronized修饰的方法。可以给出下面的例子做佐证
public class SynchronizedTest2 {
public synchronized void method1() {
System.out.println("Method 1 start");
try {
System.out.println("Method 1 execute");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method 1 end");
}
public void method2() {
System.out.println("Method 2 start");
try {
System.out.println("Method 2 execute");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method 2 end");
}
public static void main(String[] args) {
final SynchronizedTest2 test = new SynchronizedTest2();
new Thread(test::method1).start();
new Thread(test::method2).start();
}
}
从输出结果看到当线程1还在执行时,线程2也执行了,所以当其他线程来访问非synchronized修饰的方法时是可以访问的。
Method 1 start
Method 2 start
Method 1 execute
Method 2 execute
Method 2 end
Method 1 end
多个线程访问不同对象同一同步方法
此时两个线程的锁对象是不同的SynchronizedTest实例
public class SynchronizedTest {
public synchronized void method1() {
System.out.println("Method 1 start");
try {
System.out.println("Method 1 execute");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method 1 end");
}
public synchronized void method2() {
System.out.println("Method 2 start");
try {
System.out.println("Method 2 execute");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method 2 end");
}
public static void main(String[] args) {
final SynchronizedTest test1 = new SynchronizedTest();
final SynchronizedTest test2 = new SynchronizedTest();
new Thread(test1::method1).start();
new Thread(test2::method2).start();
}
}
这种情况无法保证两个线程的执行顺序,因为两个线程作用于不同的对象,获得的是不同的锁,所以互相并不影响。但是如果两个线程传入的都是test1::method1,即同一对象的不同同步方法,只有当第一个线程执行结束,第二个线程才能获得执行权。
Method 1 start
Method 1 execute
Method 2 start
Method 2 execute
Method 2 end
Method 1 end
结论
当两个线程同时对一个对象的同一个同步方法进行操作,只有一个线程能够抢到锁。因为一个对象只有一把锁,一个线程获取了该对象的锁之后,其他线程无法获取该对象的锁,就不能访问该对象的其他synchronized实例方法,线程将阻塞。等到对象锁被释放后才能获取。
静态同步方法
public class synchronizedTest implements Runnable {
//共享资源
static int i =0;
/**
* synchronized 修饰实例方法
*/
public static synchronized void increase(){
i++;
}
@Override
public void run(){
for (int j =0 ; j<10000;j++){
increase();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new synchronizedTest());
Thread t2 = new Thread(new synchronizedTest());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
由例子可知,两个线程实例化两个不同的对象,但是访问的方法是静态的,两个线程发生了互斥(即一个线程访问,另一个线程只能等着),因为静态方法是依附于类而不是对象的。当synchronized修饰静态方法时,锁是class对象。如果increase()不是静态方法,由于线程竞争执行,结果就不可预测了。