package com.consum.test; /** * 测试多线程并发 */ public class synchronizedCode implements Runnable { static synchronizedCode instance = new synchronizedCode(); static int i = 0; static String key = "1"; public static void main(String[] args) throws InterruptedException { for (int j=0;j<5;j++){ Thread t1 = new Thread(instance); t1.start(); } System.out.println("线程执行结束"); } @Override public void run() { String myKey; if (key == "1"){ myKey = "def"; key = "2"; } else { myKey = "abc"; key="1"; } System.out.println(Thread.currentThread().getName() + ":" + myKey); synchronized (myKey){ System.out.println(Thread.currentThread().getName() + "开始运行"); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("我叫"+ Thread.currentThread().getName()+"运行结束"); } } }