对象和Class
/** * synchronized 这个锁 锁的对象是方法的调用者, * 两个方法用的是同一个锁,谁先拿到谁先执行 * * */
public class WindowSell5 { public synchronized void sendMsg(){ try{ TimeUnit.SECONDS.sleep(4); }catch (Exception e){ } System.out.println("sendMsg"); } public synchronized void call(){ System.out.println("打电话"); } }
public class MainTest1 {
public static void main(String[] args) {
WindowSell5 windowSell5 = new WindowSell5();
/**
*
* 1、sendMsg 和 call谁先执行 sendMsg
* 2、sendMsg 睡4秒 谁先执行 sendMsg
*
*/
new Thread(()->{
windowSell5.sendMsg();
},"a").start();
new Thread(()->{
windowSell5.call();
},"b").start();
}
}
/**
*
*
* 一个有锁,一个没有锁,没有锁的方法它不用等待,直接就可以用
*
*/
public class WindowSell5 { public synchronized void sendMsg(){ try{ TimeUnit.SECONDS.sleep(4); }catch (Exception e){ } System.out.println("sendMsg"); } public void hello(){ System.out.println("hello"); } }
public class MainTest1 {
public static void main(String[] args) {
WindowSell5 windowSell5 = new WindowSell5();
/**
*
* 1、sendMsg 和hello谁先执行 hello
* 2、sendMsg 睡4秒 谁先执行 hello
*
*/
new Thread(()->{
windowSell5.sendMsg();
},"a").start();
new Thread(()->{
windowSell5.hello();
},"b").start();
}
}
public class WindowSell5 { /** * synchronized 这个锁 锁的对象是Class(WindowSell5) * 两个方法用的是同一个锁,谁先拿到谁先执行 * * */ public static synchronized void sendMsg(){ try{ TimeUnit.SECONDS.sleep(4); }catch (Exception e){ } System.out.println("sendMsg"); } public static synchronized void call(){ System.out.println("打电话"); } }
public class MainTest1 {
public static void main(String[] args) {
WindowSell5 windowSell5 = new WindowSell5();
/**
*
* 1、sendMsg 和 call谁先执行 sendMsg
* 2、sendMsg 睡4秒 谁先执行 sendMsg
*
*/
new Thread(()->{
windowSell5.sendMsg();
},"a").start();
new Thread(()->{
windowSell5.call();
},"b").start();
}
}
/**
*
*
* 两个都有锁,锁的对象不一样,一个是Class,一个是方法的调用者
*
*/
public class WindowSell5 { public static synchronized void sendMsg(){ try{ TimeUnit.SECONDS.sleep(4); }catch (Exception e){ } System.out.println("sendMsg"); } public synchronized void call(){ System.out.println("打电话"); } } public class MainTest1 { public static void main(String[] args) { WindowSell5 windowSell5 = new WindowSell5(); /** * * 1、sendMsg 和 call谁先执行 call * 2、sendMsg 睡4秒 谁先执行 call * */ new Thread(()->{ windowSell5.sendMsg(); },"a").start(); new Thread(()->{ windowSell5.call(); },"b").start(); } }
原文:https://www.cnblogs.com/gaohq/p/14774614.html