package com.test.test;
public class Fool {
public synchronized void m1(String h)
{
System.out.println(h);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public synchronized static void m2(String w) throws InterruptedException
{
System.out.println(w);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
final Fool foo=new Fool();
Thread t=new Thread(new Runnable() {
@Override
public void run() {
// TODO 自动生成的方法存根
foo.m1("hello");
try {
foo.m2("1");
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
});
t.start();
final Fool f=new Fool();
Thread tt=new Thread(new Runnable() {
@Override
public void run() {
// TODO 自动生成的方法存根
try {
f.m1("world");
f.m2("2");
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
});
tt.start();
}
}
Synchronized 如果修饰 static则为类锁, 修饰其他方法则为对象锁
类锁:对象访问是互斥的
对象锁:多个不同的对象访问不互斥 ,多个线程绑定相同的对象则产生互斥