什么是线程安全?
多个线程操纵变量,能保持变量的一致性,正确性,没有发生相互修改和串行的情况。
隐式锁,又称为线程同步synchronized
syschronized可以对一个方法使用,也可以对一个代码快进行使用。
public synchronized void Set(){
}
public void set(){
synchronized(this){
}
}
多个线程访问是遵循FIFO先来先用。
syschronized不用手动创建锁和释放锁。
显示锁Lock和ReentrantLock。
无条件的,可轮询的,定时的,可中断的。所有加锁和释放都是显示的。
ReentrantLock是Lock的实现类
只要对所需要加锁的地方加锁即可,可以在类中加锁也可以在类外加锁
package gavin;
public class ReentrantLockTest{
public void start(){
System.out.println(Thread.currentThread().getName()+" start");
}
public void state(){
System.out.println( Thread.currentThread().getName()+" "+Thread.currentThread().getState());
}
}
public class Main {
private static final ReentrantLock reentrantLock = new ReentrantLock();
public static void main(String[] args) throws Exception{
ReentrantLockTest test = new ReentrantLockTest();
for (int i = 0; i < 3; i++) {
new Thread(){
public void run (){
reentrantLock.lock();
test.start();
reentrantLock.unlock();
}
}.start();
}
for (int i = 0; i < 3; i++) {
new Thread(){
public void run(){
reentrantLock.lock();
test.state();
reentrantLock.unlock();
}
}.start();
}
}
}
import java.util.concurrent.locks.ReentrantReadWriteLock;
class Count{
private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
public void get(){
rwl.readLock().lock();
try{
System.out.println(Thread.currentThread().getName()+" start");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" end");
}catch(InterruptedException e){
e.printStackTrace();
}
finally{
rwl.readLock().unlock();
}
}
public void set(){
rwl.writeLock().lock();
try{
System.out.println(Thread.currentThread().getName()+" write Thread start");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+" write Thread end");
}catch(InterruptedException e){
e.printStackTrace();
}
finally{
rwl.writeLock().unlock();
}
}
}
读写锁,读读不互斥,读写互斥,写写互斥。