java常用锁
ReadAndWriteLock
package AboutSysn;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadAndWriteLock {
static ReentrantLock reLock = new ReentrantLock();
static ReadWriteLock rwLock = new ReentrantReadWriteLock();
static Lock writeLock = rwLock.writeLock();
static Lock readLock = rwLock.readLock();
static void sleepTime() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static void read(Lock lock)
{
lock.lock();
try {
System.out.println("开始读");
System.out.println("read");
System.out.println("读完了");
} catch (Exception e) {
// TODO: handle exception
}finally {
lock.unlock();
System.out.println("读释放");
}
}
static void write(Lock lock) throws Exception
{
lock.lock();
try {
System.out.println("开始写");
System.out.println("write");
System.out.println("写完了");
} catch (Exception e) {
}finally {
//if(locked) lock.unlock();
lock.unlock();
}
}
static void nonLock() {
System.out.println("nonLock"); //会立即执行
}
public static void main(String[] args) throws Exception{
for(int i=0;i<180;i++) {
new Thread(()->{
//read(reLock); //ReentrantLock锁,其他的线程执行需要等待当前线程完成,并且此时这个锁资源被占用,在其他地方使用这个锁也需要等待释放
read(readLock); //rwLock.readLock();其他的读线程可以同时执行,但是读的时候被锁定的资源不能写,因为是从同一个ReentrantReadWriteLock获取的读写锁,所以他们不会同时执行
}).start();;
}
for(int i=0;i<200;i++) {
new Thread(()->{
try {
write(writeLock); //独占
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}).start();;
}
nonLock();
}
}
总结:
常见常用,需要熟练掌握
Semaphore
package AboutSysn;
import java.util.concurrent.Semaphore;
public class SemaphoreDemo {
public static void main(String[] args) {
//限制同时只能有一个线程执行
Semaphore sp = new Semaphore(1);
for(int i=0;i<5;i++)
{
new Thread(()->{
try {
sp.acquire(); //当前线程获取执行权限
System.out.println(Thread.currentThread().getName()); //每个1S输出一次
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
sp.release(); //当前线程释放执行权限
}
}).start();
}
}
}
//结果 每个结果间隔1S
Thread-0
Thread-1
Thread-2
Thread-3
Thread-4
LockSupport
package AboutSysn;
import java.util.concurrent.locks.LockSupport;
public class LockSupportDemo {
public static void main(String[] args) {
Thread t1 = new Thread(()->{
System.out.println("BeforeLockSupport");
LockSupport.park();
System.out.print("afterLockSupport");//2S 后被main线程释放
});
t1.start();
try {
Thread.sleep(2000);
//此时放开上面的park
LockSupport.unpark(t1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//结果
BeforeLockSupport
这里间隔了2S
afterLockSupport