- 1 public class TestSynchronized {
- 2 private InClass inClass = new InClass("name");
- 3 4 public void test1() {
- 5 synchronized(inClass) {
- 6 int i = 5;
- 7
- while (i-->0) {
- 8 System.out.println(Thread.currentThread().getName() + " : " + i);
- 9
- try {
- 10 Thread.sleep(500);
- 11
- } catch(InterruptedException ie) {
- 12
- }
- 13
- }
- 14
- }
- 15
- }
- 16 17 public synchronized void test2() {
- 18 19 int i = 5;
- 20
- while (i-->0) {
- 21 System.out.println(Thread.currentThread().getName() + " : " + i);
- 22
- try {
- 23 Thread.sleep(500);
- 24
- } catch(InterruptedException ie) {
- 25
- }
- 26
- }
- 27 28
- }
- 29 30 public void test3() {
- 31 synchronized(TestSynchronized.class) {
- 32 int i = 5;
- 33
- while (i-->0) {
- 34 System.out.println(Thread.currentThread().getName() + " : " + i);
- 35
- try {
- 36 Thread.sleep(500);
- 37
- } catch(InterruptedException ie) {
- 38
- }
- 39
- }
- 40
- }
- 41
- }
- 42 43 public void test4() {
- 44 synchronized(this) {
- 45 int i = 5;
- 46
- while (i-->0) {
- 47 System.out.println(Thread.currentThread().getName() + " : " + i);
- 48
- try {
- 49 Thread.sleep(500);
- 50
- } catch(InterruptedException ie) {
- 51
- }
- 52
- }
- 53
- }
- 54
- }
- 55 56 public synchronized void test5() {
- 57 58 int i = 5;
- 59
- while (i-->0) {
- 60 System.out.println(Thread.currentThread().getName() + " : " + i);
- 61
- try {
- 62 Thread.sleep(500);
- 63
- } catch(InterruptedException ie) {
- 64
- }
- 65
- }
- 66 67
- }
- 68 69 public static void main(String[] args) {
- 70 final TestSynchronized myt1 = new TestSynchronized();
- 71 final TestSynchronized myt2 = new TestSynchronized();
- 72 Thread test1 = new Thread(new Runnable() {
- 73 public void run() {
- 74 myt1.test2();
- 75
- }
- 76
- },
- "test1");
- 77
- try {
- 78 Thread.sleep(10);
- 79
- } catch(InterruptedException e) {
- 80 // TODO 自动生成的 catch 块
- 81 e.printStackTrace();
- 82
- }
- 83 Thread test2 = new Thread(new Runnable() {
- 84 public void run() {
- 85 myt1.test5();
- 86
- }
- 87
- },
- "test2");
- 88 test1.start();
- 89 test2.start();
- 90
- }
- 91 92 class InClass {
- 93 public InClass(String name) {
- 94 // TODO 自动生成的构造函数存根
- 95
- }
- 96
- }
- 97
- }
来源: