package com.jack.zhang.chapter9.classlock; /** * * @author EX-LIUQI001 * */ public class Test { public static synchronized void staticX() throws InterruptedException { for (int i = 0; i < 10; i++) { Thread.sleep(1000); System.out.println("staticX......................."); } } public synchronized void x() throws InterruptedException { for (int i = 0; i < 10; i++) { Thread.sleep(1000); System.out.println("x......................."); } } public static void main(String[] args) { final Test test1 = new Test(); Thread thread = new Thread(new Runnable() { public void run() { try { test1.x(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }, "a"); Thread thread1 = new Thread(new Runnable() { public void run() { try { Test.staticX(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }, "b"); thread1.start(); thread.start(); } }
package com.jack.zhang.chapter9.classlock; /** * * @author EX-LIUQI001 * */ public class Test2 { public final static Byte[] locks = new Byte[0]; public static void staticX() throws InterruptedException { synchronized (locks) { for (int i = 0; i < 10; i++) { Thread.sleep(1000); System.out.println("staticX......................."); } } } public void x() throws InterruptedException { synchronized (locks) { for (int i = 0; i < 10; i++) { Thread.sleep(1000); System.out.println("x......................."); } } } public static void main(String[] args) { final Test2 test1 = new Test2(); Thread thread = new Thread(new Runnable() { public void run() { try { test1.x(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }, "a"); Thread thread1 = new Thread(new Runnable() { public void run() { try { Test2.staticX(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }, "b"); thread1.start(); thread.start(); } }
原文地址:http://blog.csdn.net/u011742227/article/details/42497347