Lock接口
ReentrantLock
lock()
unlock()
class Ticket implements Runnable {
int count =10;
//Object lock = new Object();
private Lock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
try{
lock.lock();
if(count>0){
System.out.println("票:"+count--+"thread:"+Thread.currentThread());
}else {
break;
}
}catch (Exception ex){}
finally{
lock.unlock();
}
}
}
}
死锁
线程1 线程2 资源A 资源B
线1:拿A资源要请求B
但是同时 线2:拿B资源请求A资源
但是A被1🔒了 B被2🔒了
就都在等待释放 。。。就死锁了
🐷解决方案:
1:同时申请A和B 🔒住资源
2: 如果都要用A和B —》那就都按照一定的顺序🔒,eg:先锁A再锁B
低级通讯
- wait. 配合synchronized使用。 释放自身封锁对象 自身阻塞
- notify 🔒会放开
- notifyAll
synchronized(a){
a.wait();
XXXXXXX
a.notify/notifyAll(); //前者会唤醒,第一个因为a.wait()阻塞的线程
}
Thread thread1(()->{
synchronized(goods){
if(goods.size>0){
good.wait();
}else{
//生产
}
}
})
Thread thread2(()->{
synchronized(goods){
if(goods.size<=0){
good.notify();
}
else{
//消费
}
}
})
Executor接口
线程池
class MyThread3 implements Callable<Object>{
@Override
public Object call() throws Exception {
int i;
for ( i=0;i<10;i++){
System.out.println(Thread.currentThread());
}
return i;
}
}
调用:
public static void main(String[] args) throws ClassNotFoundException, SQLException, ExecutionException, InterruptedException {
MyThread4 thread4 = new MyThread4();
ExecutorService executor = Executors.newCachedThreadPool();
Future<Object> res1 = executor.submit(thread4);
executor.shutdown();
}