+ ":synchronized in Method3("+i+")");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
//初始化Test1对象
final AbstractTest ts = new Test1();
//线程1
Thread1 thread1=new Thread1(ts);
thread1.start();
//线程2
Thread2 thread2=new Thread2(ts);
thread2.start();
//线程3
Thread3 thread3=new Thread3(ts);
thread3.start();
//main线程
ts.Method3();
}
}
package com.jialin;
import java.util.concurrent.TimeUnit;
/**
* 测试java 锁
* @author jialin
*
*/
public class Test1 extends AbstractTest{
public void Method1() {
//-----这一部分未加锁,可以运行到------begin---
System.out.println(Thread.currentThread().getName()
+ ":not synchronized part in Method1()");
//-----这一部分未加锁,可以运行到------end---
synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in Method1("+i+")");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void Method2() {
//-----这一部分未加锁,可以运行到------begin---
System.out.println(Thread.currentThread().getName()
+ ":not synchronized part in Method2()");
//-----这一部分未加锁,可以运行到------end---
synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in Method2("+i+")");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void Method3() {
//-----这一部分未加锁,可以运行到------begin---
System.out.println(Thread.currentThread().getName()
+ ":not synchronized part in Method3()");
//-----这一部分未加锁,可以运行到------end---
synchronized (this) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":synchronized in Method3("+i+")");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
//初始化Test1对象
final AbstractTest ts = new Test1();
//线程1
Thread1 thread1=new Thread1(ts);
thread1.start();
//线程2
Thread2 thread2=new Thread2(ts);
thread2.start();
//线程3
Thread3 thread3=new Thread3(ts);
thread3.start();
//main线程
ts.Method3();
}
}
运行结果:
Thread-0:not synchronized part in Method1()
Thread-0:synchronized in Method1(0)
main:not synchronized part in Method3()
Thread-1:not synchronized part in Method2()
Thread-2:not synchronized part in Method3()
Thread-0:synchronized in Method1(1)
Thread-0:synchronized in Method1(2)
Thread-0:synchronized in Method1(3)
Thread-0:synchronized in Method1(4)
Thread-2:synchronized in Method3(0)
Thread-2:synchronized in Method3(1)
Thread-2:synchronized in Method3(2)
Thread-2:synchronized in Method3(3)
Thread-2:synchronized in Method3(4)
Thread-1:sync