12 多线程同步2(synchronized )

接 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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值