//修飾一個塊
syschronized(一個對象) { 。。。。 }
java中的每個對象都有一個鎖(lock),或者叫監視器,當這個對象訪問一個synchronized方法的時候,表示將這個對象上鎖,此時其它任何線程都沒法再去訪問這個synchronized方法了!直到以前那個線程執行完畢方法後或者拋出異常,那麼將該對象的鎖釋放掉,其它線程就能夠訪問該synchronized方法。
package com.yuxi.lesson102; public class SynchronizedDemo { public static void main(String[] args) { Event event = new Event(); Event event2 = new Event(); MyThread1 myThread = new MyThread1(event); MyThread2 myThread2 = new MyThread2(event2); new Thread(myThread).start(); new Thread(myThread2).start(); Event.doThingOne(); } } class Event { public static synchronized void doThingOne() { for (int i = 0; i <20; i++) { try { Thread.sleep((long) (Math.random()*100)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("事情1正在作"+i); } System.out.println("作完了事情1"); } public synchronized void doThingTwo() { for (int i = 0; i <20; i++) { try { Thread.sleep((long) (Math.random()*100)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("事情2正在作"+i); } System.out.println("作完了事情2"); } } class MyThread1 implements Runnable { private Event event; public MyThread1(Event event) { this.event = event; } @Override public void run() { this.event.doThingOne(); } } class MyThread2 implements Runnable { private Event event; public MyThread2(Event event) { this.event = event; } @Override public void run() { this.event.doThingOne(); } }