java線程同步方法,方法塊區別,java線程同步區別

來源:互聯網
上載者:User

java線程同步方法,方法塊區別,java線程同步區別

先說同步方法,它到底是鎖定的當前對象,還是當前類

代碼塊1

package com.ssss;public class Thread1 implements Runnable {  //public static Object  o=new Object();    public void run() {    pt();    }        public synchronized void pt(){    int a=0;        //synchronized(o) {               for (int i = 0; i < 5; i++) {             a++;             try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}                  System.out.println(Thread.currentThread().getName() + " synchronized loop " + i + "++++" + a);               }          //}      }            public static void main(String[] args) {           Thread1 t1 = new Thread1();           Thread1 t2 = new Thread1();           Thread ta = new Thread(t1, "A");           Thread tb = new Thread(t2, "B");           ta.start();           tb.start();      } }

列印出來的結果為


由此可見是當前對象,而A和B是兩個不同的對象,所以列印序列就是混亂的


代碼塊2

看同步塊

package com.ssss;public class Thread1 implements Runnable {  public static Object  o=new Object();    public void run() {    pt();    }        public void pt(){    int a=0;        synchronized(o) {               for (int i = 0; i < 5; i++) {             a++;             try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}                  System.out.println(Thread.currentThread().getName() + " synchronized loop " + i + "++++" + a);               }          }      }            public static void main(String[] args) {           Thread1 t1 = new Thread1();           Thread1 t2 = new Thread1();           Thread ta = new Thread(t1, "A");           Thread tb = new Thread(t2, "B");           ta.start();           tb.start();      } }

看列印序列


說明同步塊可以鎖定任何對象


就是說同步方法是鎖定當前對象,同步方法塊是可以鎖定任何對象



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.