synchronized介绍
private final Object mutes =null;
public void syncMethod(){
synchronized(mutes){
}
}
public static void main(String[] args) {
ThreadSynchronizedTest t = new ThreadSynchronizedTest();
new Thread(t::method1,"线程1").start();
new Thread(t::method2,"线程2").start();
}
public synchronized void method1() {
System.out.println(Thread.currentThread().getName()+"执行1");
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized void method2() {
System.out.println(Thread.currentThread().getName()+"执行2");
try {
TimeUnit.MINUTES.sleep(2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class monitor
使用synchronized 关键字同步类的不同static方法,争抢的是同一个monitor的lock,与之关联的引用是ClassMonitor;同步方法内的代码块也是一样的。
public static void main(String[] args) {
new Thread(ThreadSynchronizedTest::method1,"线程1").start();
new Thread(ThreadSynchronizedTest::method2,"线程2").start();
}
public static synchronized void method1() {
System.out.println(Thread.currentThread().getName()+"执行1");
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static synchronized void method2() {
System.out.println(Thread.currentThread().getName()+"执行2");
try {
TimeUnit.MINUTES.sleep(2);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
程序死锁的原因
本文地址:https://blog.csdn.net/pys52055/article/details/107355993
如对本文有疑问, 点击进行留言回复!!
before社区电量是什么意思 Before社区电量获得方法
RecycleView入门详解(教你全面掌握RecycleView用法)
动态权限请求框架RxPermissions(几行代码搞定权限)
URL路径@PathVariable出现点号“.“时值遭截断问题
网友评论