一.死锁
1.什么是死锁?
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行 ,而倒置两个或多个线程都在等待对方释放资源,都停止执行,某一同步块同时拥有两个以上对象的锁,发生了“死锁”问题 。 举个栗子:现在有两个女孩需要化妆,化妆工具有口红(lipstick),镜子(mirror)。用两个线程代替两个女生,看一下代码:
package synchronize ;
public class LockTest {
public static void main ( String [ ] args) {
MakeUp girl1= new MakeUp ( 0 , "girl1" ) ;
MakeUp girl2 = new MakeUp ( 1 , "girl2" ) ;
girl1. start ( ) ;
girl2. start ( ) ;
}
}
class lipstick { }
class Mirror { }
class MakeUp extends Thread {
static lipstick lipstick = new lipstick ( ) ;
static Mirror mirror = new Mirror ( ) ;
int choice;
String girlName;
MakeUp ( int choice, String girlName) {
this . choice = choice;
this . girlName = girlName;
}
@Override
public void run ( ) {
try {
makeup ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
private void makeup ( ) throws InterruptedException {
if ( choice == 0 ) {
synchronized ( lipstick) {
System . out. println ( this . girlName+ "获得口红的锁" ) ;
Thread . sleep ( 1000 ) ;
}
synchronized ( mirror) {
System . out. println ( this . girlName+ "获得镜子的锁" ) ;
}
} else {
synchronized ( mirror) {
System . out. println ( this . girlName+ "获得镜子的锁" ) ;
Thread . sleep ( 2000 ) ;
}
synchronized ( lipstick) {
System . out. println ( this . girlName+ "获得口红的锁" ) ;
}
}
}
}
2.死锁是怎样产生的?
1.一个资源每次只能被一个线程使用 2.一个线程因请求资源而阻塞时,对已获得的资源保持不放 3.线程已获得的资源在未使用之前,不能强行剥夺
二.Lock锁(java.util.concurrent.locks.Lock)
Java提供了一种更强大的线程同步机制————通过显式定义同步锁来实现同步(lock) 。 每次只能有一个线程对Lock对象加锁,线程开始访问共享资源前应先获得Lock对象 。 ReentrantLock(可重入锁)类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,ReentrantLock,可以进行显示加锁,释放锁。 举个栗子,买票,加入可重入锁
package senior ;
import java. util. concurrent. locks. ReentrantLock ;
public class lockTest {
public static void main ( String [ ] args) {
lockTest02 lockTest02 = new lockTest02 ( ) ;
new Thread ( lockTest02) . start ( ) ;
new Thread ( lockTest02) . start ( ) ;
new Thread ( lockTest02) . start ( ) ;
}
}
class lockTest02 implements Runnable {
int ticketNums = 10 ;
private final ReentrantLock lock = new ReentrantLock ( ) ;
@Override
public void run ( ) {
while ( true ) {
try {
lock. lock ( ) ;
if ( ticketNums > 0 ) {
try {
Thread . sleep ( 1000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
System . out. println ( ticketNums-- ) ;
} else { break ; }
} finally {
lock. unlock ( ) ;
}
}
}
}
synchronized与Lock
Lock是显式锁(手动开启,手动关闭 ),synchronized是隐式锁,出了作用域会自动释放 Lock锁只有代码块锁,synchronized有代码块锁和方法锁 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好,并且具有更好的扩展性