hronized in Method2(0)
Thread-1:synchronized in Method2(1)
Thread-1:synchronized in Method2(2)
Thread-1:synchronized in Method2(3)
Thread-1:synchronized in Method2(4)
main:synchronized in Method3(0)
main:synchronized in Method3(1)
main:synchronized in Method3(2)
main:synchronized in Method3(3)
main:synchronized in Method3(4)
[java]
package com.jialin;
import java.util.concurrent.TimeUnit;
public class Test2 extends AbstractTest {
public synchronized void Method1() {
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() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":no synchronized in Method2("+i+")");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void Method3() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":no 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 Test2();
// 线程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.Method1();
}
}
package com.jialin;
import java.util.concurrent.TimeUnit;
public class Test2 extends AbstractTest {
public synchronized void Method1() {
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() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":no synchronized in Method2("+i+")");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void Method3() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()
+ ":no 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 Test2();
// 线程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.Method1();
}
}
运行结果: