日期:2014-05-20 浏览次数:20612 次
public class TestThread { public static void main(String[] args) { Runner r1 = new Runner(); r1.flag = 1; //标示,运行m1方法 Thread t1 = new Thread(r1); t1.start(); Runner r2 = new Runner(); r2.flag = 2; //标示,运行m2方法 Thread t2 = new Thread(r2); t2.start(); } } class Runner implements Runnable { static String str = "哈哈"; int flag = 0; public void run() { try { if(flag == 1) { m1(); } if(flag == 2) { m2(); } } catch (Exception e) { e.printStackTrace(); } } public void m1() throws Exception { synchronized(str) { str = "m1"; Thread.sleep(1000); System.out.println("1:" + str); } } public void m2() throws Exception { synchronized(str) { str = "m2"; Thread.sleep(1000); System.out.println("2:" + str); } } }