线程安全和线程锁的源码及其应用
1.同步(synchronization)
synchronized 有以下两种使用方式:
synchronized 代码块。synchronized(object) 在对某个对象上执行加锁时,会尝试在该对象的监视器上进行加锁操作,只有成功获取锁之后,线程才会继续往下执行。线程获取到了监视器锁后,将继续执行 synchronized 代码块中的代码,如果代码块执行完成,或者抛出了异常,线程将会自动对该对象上的监视器执行解锁操作。
synchronized 作用于方法,称为同步方法。同步方法被调用时,会自动执行加锁操作,只有加锁成功,方法体才会得到执行。如果被 synchronized 修饰的方法是实例方法,那么这个实例的监视器会被锁定。如果是 static 方法,线程会锁住相应的 Class 对象的监视器。方法体执行完成或者异常退出后,会自动执行解锁操作。
代码如下:
public class MySyschronizedTest {
public void test1()
{
synchronized(this)
{
int i = 5;
while( i-- > 0)
{
System.out.println(Thread.currentThread().getName() + " : " + i);
try
{
Thread.sleep(500);
}
catch (InterruptedException ie)
{
}
}
}
}
public synchronized void test2()
{
int i = 5;
while( i-- > 0)
{
System.out.println(Thread.currentThread().getName() + " : " + i);
try
{
Thread.sleep(500);
}
catch (InterruptedException ie)
{
}
}
}
public static void main(String[] args)
{
final MySyschronizedTest mytest = new MySyschronizedTest();
Thread test1 = new Thread( new Runnable() { public void run() { mytest.test1(); } }, "test1" );
Thread test2 = new Thread( new Runnable() { public void run() { mytest.test2(); } }, "test2" );
test1.start();
mytest.test2();
test2.start();
注意:main方法先执行,之后是test1,最后是test2。
2等待集合 和 唤醒(Wait Sets and Notification)
2.1等待 (Wait)
作用:wait方法会使线程进入阻塞状态。并等待被唤醒或者等待时间结束。
方法:wait(),wait(long millisecs),wait(long millisecs, int nanosecs)。
假设:线程 t 中对对象 m 调用 m.wait() 方法,n 代表加锁编号(n为是否持有对象锁)
注意点:n为是否持有对象锁
1.如果 n 等于 0(如线程 t 没有持有对象 m 的锁),那么会抛出 IllegalMonitorStateException 异常。
2.如果线程 t 被中断,此时中断状态为 true,则 wait 方法将抛出 InterruptedException 异常,并将中断状态设置为 false。(中断是将线程的status设置为true,不是直接中断线程。)
3.如果线程 t 调用的是 m.wait(millisecs) 或m.wait(millisecs, nanosecs),形参 millisecs 不能为负数,nanosecs 取值应为 [0, 999999],否则会抛出
IllegalArgumentException 异常。
在 m上执行了 notify 操作,而且线程 t 被选中从等待集合中移除。
在 m 上执行了 notifyAll 操作,那么线程 t 会从等待集合中移除。
重点:
1.总而言之如果没有获取对象锁,wait 方法是会抛异常的或者继续阻塞,而且注意这个异常是IllegalMonitorStateException 异常。这是重要知识点。
2.wait方法必须放在syschronized里面
个人理解wait方法是这么用的:
synchronized(m) {
while(!canExit) {
m.wait(10); // 等待10ms; 当然中断也是常用的
boolean canExit = something(); // 判断是否可以退出循环
}
}
2.2通知(Notification)
作用:唤醒线程进入runnable或者running状态。
方法:
1.notify只会通知一个在等待的对象,
2.notifyAll会通知所有在等待的对象,并且所有对象都会继续运行
2.3中断(Interruptions)
作用:将线程的状态status设为true,并使该线程dead
2.4加入(join)
用于start方法后面,表示该线程执行完才能执行之前的线程
使用代码:
ThreadJoinTest t1 = new ThreadJoinTest("小明");
ThreadJoinTest t2 = new ThreadJoinTest("小东");
t1.start();
t1.join();
t2.start();
线程t1、线程t2使得原来公平争抢,变成了线程t1调用join的这个线程,线程t1拥有了更高的权限(t1线程跑完了,t2才会走)
下面使用代码说明2.1到2.4的知识点
public class WaitNotify3 {
volatile int a = 0;
public static void main(String[] args) {
final Object object = new Object();
final WaitNotify3 waitNotify = new WaitNotify3();
final Thread thread1 = new Thread(new Runnable() {
public void run() {
synchronized (object) {
System.out.println("线程1 获取到监视器锁");
try {
object.wait();
System.out.println("线程1 正常恢复啦。");
} catch (InterruptedException e) {
System.out.println("线程1 wait方法抛出了InterruptedException异常");
}
}
}
}, "线程1");
thread1.start();
Thread thread2 = new Thread(new Runnable() {
public void run() {
synchronized (object) {
System.out.println("线程2 获取到监视器锁");
try {
object.wait();
System.out.println("线程2 正常恢复啦。");
} catch (InterruptedException e) {
System.out.println("线程2 wait方法抛出了InterruptedException异常");
}
}
}
}, "线程2");
thread2.start();
// 这里让 thread1 和 thread2 先起来,然后再起后面的 thread3
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
new Thread(new Runnable() {
public void run() {
synchronized (object) {
System.out.println("线程3 拿到了监视器锁。");
System.out.println("线程3 设置线程1中断");
thread1.interrupt(); // 1
waitNotify.a = 1; // 这行是为了禁止上下的两行中断和notify代码重排序
System.out.println("线程3 调用notify");
object.notify(); //2
System.out.println("线程3 调用完notify后,休息一会");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
System.out.println("线程3 休息够了,结束同步代码块");
}
}
}, "线程3").start();
}
}
运行结果
3.休眠和礼让(Sleep and Yield)
作用:使当前正在执行的线程休眠指定的一段时间
方法:Thread.sleep(millisecs);
yield 是告诉操作系统的调度器:我的cpu可以先让给其他线程。注意,调度器可以不理会这个信息。
这个方法太鸡肋,几乎没用。