????
示例:
?
class="java" name="code">package com.zan; /** * 关键字synchronized取得的锁都是对象锁,而不是把一段代码(方法)当做锁, * 所以代码中哪个线程先执行synchronized关键字的方法,哪个线程就持有该方法所属对象的锁(Lock), * * 在静态方法上加synchronized关键字,表示锁定.class类,类一级别的锁(独占.class类)。 * */ public class MultiThread { private static int num = 0; // static public static synchronized void print(String flag){ try { if(flag.equals("a")){ num = 100; System.out.println("falg a, set 100 over!"); Thread.sleep(1000); } else { num = 200; System.out.println("flag b, set 200 over!"); } System.out.println("flag " + flag + ", num = " + num); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) { final MultiThread m1 = new MultiThread(); final MultiThread m2 = new MultiThread(); new Thread(new Runnable() { @Override public void run() { m1.print("a"); } },"t1").start(); new Thread(new Runnable() { @Override public void run() { m2.print("b"); } },"t2").start(); } }
?运行结果:
?
?
?
?