1.问题
synchronized是锁,但是锁住的内容究竟是对象还是方法。
2.测试
测试代码1(声明方法时加入synchronized):
public class MainActivity {
public static void main(String[] args) {
Thread thread1 = new Demo();//创建两个对象
Thread thread2 = new Demo();
thread1.start();
thread2.start();
}
}
class Demo extends Thread {
public static int i = 1;
@Override
public synchronized void run()
{
try {
Thread.sleep(50);
{
for(int j = 1; j <= 5; j++)
{
System.out.print("线程ID:"+Thread.currentThread().getId()+"打印"+i++ +"\n");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
测试代码2(加入synchronized (this)):
public class MainActivity {
public static void main(String[] args) {
Thread thread1 = new Demo();
Thread thread2 = new Demo();
thread1.start();
thread2.start();
}
}
class Demo extends Thread {
public static int i = 1;
@Override
public void run() {
synchronized (this)
{
try {
Thread.sleep(50);
{
for (int j = 1; j <= 5; j++) {
System.out.print("线程ID:" + Thread.currentThread().getId() + "打印" + i++ + "\n");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
测试代码3(加入synchronized (Demo.class)):
public class MainActivity {
public static void main(String[] args) {
Thread thread1 = new Demo();
Thread thread2 = new Demo();
thread1.start();
thread2.start();
}
}
class Demo extends Thread {
public static int i = 1;
@Override
public void run() {
synchronized (Demo.class)
{
try {
Thread.sleep(50);
{
for (int j = 1; j <= 5; j++) {
System.out.print("线程ID:" + Thread.currentThread().getId() + "打印" + i++ + "\n");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
结果预测:
如果锁的是方法,输出结果则应该为前5个线程ID相同,后5个线程ID相同,每次测试均是如此。
如果锁的是对象,输出结果则应该为乱序排列。
测试1结果:
线程ID:12打印2
线程ID:11打印1
线程ID:11打印3
线程ID:11打印4
线程ID:11打印5
线程ID:11打印6
线程ID:12打印7
线程ID:12打印8
线程ID:12打印9
线程ID:12打印10
测试2结果:
线程ID:12打印1
线程ID:12打印3
线程ID:11打印2
线程ID:12打印4
线程ID:12打印6
线程ID:12打印7
线程ID:11打印5
线程ID:11打印8
线程ID:11打印9
线程ID:11打印10
测试3结果(多次测试结果均是):
线程ID:11打印1
线程ID:11打印2
线程ID:11打印3
线程ID:11打印4
线程ID:11打印5
线程ID:12打印6
线程ID:12打印7
线程ID:12打印8
线程ID:12打印9
线程ID:12打印10
3.结论
显而易见,,synchronized,synchronized (this)锁的是对象,synchronized (Demo.class)锁的是方法。