JAVA中的锁
在JAVA只有一种锁,对象锁。如果按照对象的类型细分,又分为实例对象锁和Class对象
锁。即我们常称的,对象锁与类锁。
一把钥匙开一把锁
锁的作用就是防止意外情况的发生,把门一锁就是干,干完开锁还钥匙走人,下一个继续
实例对象锁
public class SyncInThread {
static class SyncInClassInstance implements Runnable {
private Integer a = 0;
@Override
public void run() {
_run();
}
private synchronized void _run(){
a += 1;
System.out.println(Thread.currentThread().getName()+":a="+a);
}
}
public static void main(String[] args) throws InterruptedException {
SyncInClassInstance syncTest = new SyncInClassInstance() ;
Thread t1 = new Thread(syncTest) ;
t1.start();
Thread t2 = new Thread(syncTest) ;
t2.start();
Thread.sleep(1000);
}
}
**效果:**无论线程谁先谁后,对象里a变量方法是按照顺序来的
Thread-1:a=1
Thread-0:a=2
Process finished with exit code 0
类锁【Class对象锁】
public class SyncInThread {
static class SyncInClassInstance implements Runnable {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName()+"正在获取SyncTest类锁");
_run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private synchronized void _run() throws InterruptedException {
synchronized(SyncTest.class){
System.out.println(Thread.currentThread().getName()+"已获取SyncTest类锁");
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName()+"已释放SyncTest类锁");
}
}
}
public static void main(String[] args) throws InterruptedException {
SyncInClassInstance syncTest = new SyncInClassInstance() ;
Thread t1 = new Thread(syncTest) ;
t1.start();
SyncInClassInstance syncTest2 = new SyncInClassInstance() ;
Thread t2 = new Thread(syncTest2) ;
t2.start();
Thread.sleep(1000);
}
}
**效果:**本例以语句块方式同步类对象,多个对象实例也要配对等钥匙
Thread-0正在获取SyncTest类锁
Thread-1正在获取SyncTest类锁
Thread-1已获取SyncTest类锁
Thread-1已释放SyncTest类锁
Thread-0已获取SyncTest类锁
Thread-0已释放SyncTest类锁
Process finished with exit code 0
本文深入解析JAVA中的锁机制,包括实例对象锁与类锁的概念、使用及效果展示。通过具体代码示例,演示了如何利用synchronized关键字实现线程同步,确保数据的一致性和线程安全。
3668

被折叠的 条评论
为什么被折叠?



