java中synchronized的使用

synchronized简单介绍
1.修饰一个代码块,被修饰的代码块称为同步语句块,其作用的范围是大括号{}括起来的代码,作用对象是调用这个代码块的对象。
2.修饰一个方法,被修饰的方法称为同步方法,作用范围是整个方法,作用对象是调用这个方法的对象。
3.修饰一个静态方法,其作用的范围是整个静态方法,作用对象是这个类的所有对象。
4修饰一个类,作用范围是大括号{}括起来的代码,作用的对象是这个类的所有对象。

一、修饰一个代码块

当一个代码块被synchronized修饰时,该代码块只能被一个线程访问,其他试图访问的线程将被阻塞。
例子 不使用synchronize关键字时

public class TestThread {
	public static void main(String[] args) {
		MyThread MyThread = new MyThread();
		Thread t1 = new Thread(MyThread);
		Thread t2 = new Thread(MyThread);
		t1.start();
		t2.start();
	}
}
class MyThread implements Runnable {
	@Override
	public void run() {
		for (int i = 0; i < 6; i++) {
			try {
				System.out.println(Thread.currentThread().getName() + ":" + i);
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

线程1和2混着出现

使用synchronize关键字时

public class TestThread {

	public static void main(String[] args) {
		MyThread MyThread = new MyThread();
		Thread t1 = new Thread(MyThread);
		Thread t2 = new Thread(MyThread);
		t1.start();
		t2.start();
	}
}

class MyThread implements Runnable {
	@Override
	public void run() {
		synchronized (this) {
			for (int i = 0; i < 6; i++) {
				try {
					System.out.println(Thread.currentThread().getName() + ":" + i);
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

线程0执行完后再执行线程1
在这里插入图片描述
当两个并发线程访问同一对象的synchronize的代码块时,同一时刻只能有一个线程执行,另一线程被阻塞,必须等当前线程执行完这个代码后才能执行此代码块。如果是不同对象,则不影响。这是因为这里的synchronized只锁定对象,每个对象只有一个锁(lock)与之相关联。
当一个线程访问对象的一个synchronized(this)同步代码块时,另一个线程仍然可以访问该对象中的非synchronized(this)同步代码块。

二、修饰方法

public class TestThread {
	public static void main(String[] args) {
		MyThread MyThread = new MyThread();
		Thread t1 = new Thread(MyThread);
		Thread t2 = new Thread(MyThread);
		t1.start();
		t2.start();
	}
}

class MyThread implements Runnable {
	@Override
	public synchronized void run() {
		for (int i = 0; i < 6; i++) {
			try {
				System.out.println(Thread.currentThread().getName() + ":" + i);
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

三、修饰静态方法或者类

修饰一个静态方法或者类,作用对象是这个类的所有对象。
所以同一类的不同对象也会是同一把锁。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值