接 12 多线程同步1(synchronized )
例子2: ThreadTester2.java
知识点:1、2;类C中的hello方法和world方法被synchronized修饰,分别给当前对象上锁,由于Thread t1和t2 是不同对象c,故hello方法和world方法上锁的对象不同;执行时,t1线程启动时,执行hello方法(睡眠5秒),此时程序继续执行,t2线程启动时,world方法执行,故结果先输出world,等5秒后,输出hello
public class ThreadTester2 {
public static void main(String[] args) {
C c = new C();
Thread t1 = new T1(c);
c = new C();
Thread t2 = new T2(c);
t1.start();
t2.start();
}
}
class C
{
public synchronized void hello()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("hello");
}
public synchronized void world()
{
System.out.println("world");
}
}
class T1 extends Thread
{
private C c;
public T1()
{}
public T1(C c)
{
this.c = c;
}
@Override
public void run() {
c.hello();
}
}
class T2 extends Thread
{
private C c;
public T2()
{}
public T2(C c)
{
this.c = c;
}
@Override
public void run() {
c.world();
}
}
运行结果:
world
(5秒后)hello
例子3: ThreadTester3.java
知识点:3;类C中的hello方法和world方法被static synchronized修饰,给当前对象的Class对象上锁,虽然Thread t1和t2 是不同对象c,但是,两者的Class对象是相同的,故hello方法和world方法上锁的对象的Class对象相同;执行时,t1线程启动时,执行hello方法(睡眠5秒),此时程序等待5秒,t2线程启动时,world方法执行,故结果等5秒后,输出hello,输出world
public class ThreadTester3 {
public static void main(String[] args) {
C c = new C();
Thread t1 = new T1(c);
t1.start();
c = new C();
Thread t2 = new T2(c);
t2.start();
}
}
class C {
public static synchronized void hello() {
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("hello");
}
public static synchronized void world() {
System.out.println("world");
}
}
class T1 extends Thread {
private C c;
public T1() {
}
public T1(C c) {
this.c = c;
}
@Override
public void run() {
c.hello();
}
}
class T2 extends Thread {
private C c;
public T2() {
}
public T2(C c) {
this.c = c;
}
@Override
public void run() {
c.world();
}
}
运行结果:
(5秒后)hello
world