[TOC]
# Java多线程相关知识【5】--锁
菜鸟的一个学习笔记,欢迎大神<font color=red>批评指正</font>。
## 1. 使用synchronized关键字
### 1. 对变量进行加锁
```java
private final static Object object = new Object();
private void lockTest() {
synchronized (object) {
//do some
}
}
```
### 2. 对函数进行加锁
```java
private synchronized void lockTest2() {
//do some
}
```
### 3. 对类进行加锁
```java
private synchronized void lockTest3() {
synchronized (this) {
//do some
}
}
```
## 2. 自实现一个LOCK
### 锁接口
```java
/**
* 锁 提供功能
*/
public interface MyLock {
class TimeOutException extends Exception{
public TimeOutException(String message) {
super(message);
}
}
/**
* 加锁
* @throws InterruptedException
*/
void lock() throws InterruptedException;
/**
* 加锁
* @param times 锁的时间毫秒
* @throws InterruptedException
* @throws TimeOutException
*/
void lock(long times) throws InterruptedException,TimeOutException;
/**
* 解锁
*/
void unLock();
/**
* 获取锁住的线程
* @return
*/
Collection<Thread> getBlockThread();
/**
* 获取锁住的数目
* @return
*/
int getBlockSize();
}
```
### 锁实现
```java
/**
* 锁实现,实现锁的功能
*/
public class MyLockImpl implements MyLock {
private boolean initValue;
private Collection<Thread> threadCollection = new ArrayList<>();
private Thread thisThread;
public MyLockImpl() {
this.initValue = false;
}
@Override
public void lock() throws InterruptedException {
while (initValue) {
threadCollection.add(Thread.currentThread());
this.wait();
}
threadCollection.remove(Thread.currentThread());
this.initValue=true;
thisThread =Thread.currentThread();
}
@Override
public void lock(long times) throws InterruptedException, TimeOutException {
if (times<=0)
lock();
long hasTime=times;
long endTime=System.currentTimeMillis()+hasTime;
while (initValue) {
if (hasTime<=0)
throw new TimeOutException("Time Out!");
threadCollection.add(Thread.currentThread());
this.wait(times);
hasTime=endTime-System.currentTimeMillis();
}
threadCollection.remove(Thread.currentThread());
this.initValue=true;
thisThread =Thread.currentThread();
}
@Override
public void unLock() {
if (Thread.currentThread()==thisThread){
this.initValue=false;
Optional.ofNullable(Thread.currentThread().getName()+" unlock!")
.ifPresent(System.out::println);
this.notifyAll();
}
}
@Override
public Collection<Thread> getBlockThread() {
return threadCollection;
}
@Override
public int getBlockSize() {
return threadCollection.size();
}
}
```