成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術文章
文章詳情頁

Java多線程之synchronized關鍵字的使用

瀏覽:3日期:2022-08-13 13:12:11
一、使用在非靜態方法上

public synchronized void syzDemo(){ System.out.println(System.currentTimeMillis()); System.out.println('進入synchronized鎖:syzDemo'); try {Thread.sleep(1000); } catch (InterruptedException e) {e.printStackTrace(); }}二、使用在靜態方法上

public synchronized static void syzDemo1(){ System.out.println(System.currentTimeMillis()); System.out.println('進入synchronized鎖:syzDemo1'); try {Thread.sleep(1000); } catch (InterruptedException e) {e.printStackTrace(); }}三、使用在代碼塊上

public synchronized void syzDemo2(){ synchronized (this){System.out.println(System.currentTimeMillis());System.out.println('進入synchronized鎖:syzDemo2');try { Thread.sleep(1000);} catch (InterruptedException e) { e.printStackTrace();} }}public synchronized void syzDemo3(){ synchronized (ExcelUtil.class){ System.out.println(System.currentTimeMillis()); System.out.println('進入synchronized鎖:syzDemo3'); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } }}四、三種方式的區別

public static void main(String[] args) {SyzDemo syzDemo = new SyzDemo();SyzDemo syzDemo1 = new SyzDemo();Thread thread = new Thread(()->{ syzDemo.syzDemo();});thread.start();Thread thread1 = new Thread(()->{ syzDemo1.syzDemo();});thread1.start(); }4.1 不會互斥

public static void main(String[] args) {SyzDemo syzDemo = new SyzDemo();SyzDemo syzDemo1 = new SyzDemo();Thread thread = new Thread(()->{ syzDemo.syzDemo();});thread.start();Thread thread1 = new Thread(()->{ syzDemo.syzDemo();});thread1.start(); }4.2 互斥

public static void main(String[] args) {SyzDemo syzDemo = new SyzDemo();SyzDemo syzDemo1 = new SyzDemo();Thread thread = new Thread(()->{ syzDemo.syzDemo1();});thread.start();Thread thread1 = new Thread(()->{ syzDemo1.syzDemo1();});thread1.start(); }

解析:

在圖1中thread1和thread分別調用syzDemo和syzDemo1對象中的syzDemo方法,因為兩個線程調用是不同的對象的兩個方法,所以不會互斥

在圖2中thread1和thread都在調用syzDemo對象中的syzDemo方法,因為syzDemo方法加了synchronized

在圖3中thread1和thread分別調用syzDemo和syzDemo1對象中的syzDemo1方法,但是因為syzDemo1方法屬于靜態方法,在類加載時就會加載到方法區,所以本質上兩個線程都在調用同一個方法,于是產生了互斥

syzDemo2中與syzDemo相同:鎖定的是當前實例的這一段代碼,只有多個線程中調用的是同一個實例且執行到這一段代碼時才會互斥,syzDemo3于syzDemo1相同:鎖定的是當前類的這一段代碼,只要多個線程共同執行這一段代碼就會產生互斥

到此這篇關于Java多線程之synchronized關鍵字的使用的文章就介紹到這了,更多相關Java synchronized關鍵字內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Java
相關文章: