synchronized简单介绍
1.修饰一个代码块,被修饰的代码块称为同步语句块,其作用的范围是大括号{}括起来的代码,作用对象是调用这个代码块的对象。
2.修饰一个方法,被修饰的方法称为同步方法,作用范围是整个方法,作用对象是调用这个方法的对象。
3.修饰一个静态方法,其作用的范围是整个静态方法,作用对象是这个类的所有对象。
4修饰一个类,作用范围是大括号{}括起来的代码,作用的对象是这个类的所有对象。
一、修饰一个代码块
当一个代码块被synchronized修饰时,该代码块只能被一个线程访问,其他试图访问的线程将被阻塞。
例子 不使用synchronize关键字时
public class TestThread {
public static void main(String[] args) {
MyThread MyThread = new MyThread();
Thread t1 = new Thread(MyThread);
Thread t2 = new Thread(MyThread);
t1.start();
t2.start();
}
}
class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 6; i++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + i);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
线程1和2混着出现
使用synchronize关键字时
public class TestThread {
public static void main(String[] args) {
MyThread MyThread = new MyThread();
Thread t1 = new Thread(MyThread);
Thread t2 = new Thread(MyThread);
t1.start();
t2.start();
}
}
class MyThread implements Runnable {
@Override
public void run() {
synchronized (this) {
for (int i = 0; i < 6; i++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + i);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
线程0执行完后再执行线程1
当两个并发线程访问同一对象的synchronize的代码块时,同一时刻只能有一个线程执行,另一线程被阻塞,必须等当前线程执行完这个代码后才能执行此代码块。如果是不同对象,则不影响。这是因为这里的synchronized只锁定对象,每个对象只有一个锁(lock)与之相关联。
当一个线程访问对象的一个synchronized(this)同步代码块时,另一个线程仍然可以访问该对象中的非synchronized(this)同步代码块。
二、修饰方法
public class TestThread {
public static void main(String[] args) {
MyThread MyThread = new MyThread();
Thread t1 = new Thread(MyThread);
Thread t2 = new Thread(MyThread);
t1.start();
t2.start();
}
}
class MyThread implements Runnable {
@Override
public synchronized void run() {
for (int i = 0; i < 6; i++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + i);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
三、修饰静态方法或者类
修饰一个静态方法或者类,作用对象是这个类的所有对象。
所以同一类的不同对象也会是同一把锁。