实现多线程同步的两种方式

为了确保在任何时间点一个共享的资源只能被一个线程使用,使用了“同步”。

一、使用同步方法
package sort;
public class Timer {
	private static int num=0;
	public synchronized void add(String name){
		num++;
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(name+"你是第 "+num+" 个使用timer的线程");
	}
}


package test;
import sort.Timer;
public class TestRunnable implements Runnable{
	Timer timer = new Timer();
	@Override
	public void run() {
		timer.add(Thread.currentThread().getName());
	}
	public static void main(String[] args) {
		TestRunnable testRunnable = new TestRunnable();
		Thread t1 = new Thread(testRunnable);
		Thread t2 = new Thread(testRunnable);
		t1.setName("t1");
		t2.setName("t2");
		t1.start();
		t2.start();
	}
}

二、使用同步代码块
package sort;
public class Timer {
	private static int num = 0;
	public void add(String name) {
		synchronized (this) {
			num++;
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(name + "你是第 " + num + " 个使用timer的线程");
		}
	}
}


package test;
import sort.Timer;
public class TestRunnable implements Runnable{
	Timer timer = new Timer();
	@Override
	public void run() {
		timer.add(Thread.currentThread().getName());
	}
	public static void main(String[] args) {
		TestRunnable testRunnable = new TestRunnable();
		Thread t1 = new Thread(testRunnable);
		Thread t2 = new Thread(testRunnable);
		t1.setName("t1");
		t2.setName("t2");
		t1.start();
		t2.start();
	}
}

两种方式运行的结果:
在这里插入图片描述
实现多线程同步的两种方式的优缺点:

- Synchronized方法
优点:可以显示的知道哪些方法是被synchronized关键字保护的
缺点:
—1.方法中有些内容是不需要同步的,如果该方法执行会花很长时间,那么其他人就会花较多时间等待锁被归还;
—2.只能取得自己对象的锁,有时候程序设计的需求,可能会需要其他对象的锁。
- Synchronized代码块
优点:
—1.可以针对某段程序代码同步,不需要浪费时间在别的程序代码上;
—2.可以取得不同对象的锁。
缺点:无法显示的得知哪些方法是被synchronized关键字保护的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值