package com.i9i.rpc;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadTest {
static ThreadPoolExecutor executor = new ThreadPoolExecutor(12, 100, 100000, TimeUnit.MINUTES,
new ArrayBlockingQueue<>(1000));
public static void main(String[] args) throws InterruptedException {
// interrupt2();
condition();
}
public static void condition() {
Lock lock=new ReentrantLock();
Condition condition=lock.newCondition();//condition必须配合lock一起产生作用
AtomicInteger count=new AtomicInteger();
Runnable comsumer=()->{
Long id=Thread.currentThread().getId();
while(true) {
lock.lock();
try {
if(count.get()<1) { //条件不满足的时候进入等待
System.out.println(id+" comsumer await");
condition.await();//释放锁,并wait
continue; //必须重新进入检测不然会出现超卖
}
System.out.println(id+" comsumer "+(count.getAndDecrement()));
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
Thread.yield();//为了均衡,让出线程执行
}
}
};
Runnable producer=()->{
while(true) {
lock.lock();
try {
System.out.println("produce 100");
count.getAndAdd(100);
condition.signalAll(); //通知其他线程,条件可能满足了,进行唤醒,必须和lock获取锁之后执行
}finally {
lock.unlock();
try {
TimeUnit.SECONDS.sleep(5); //不会释放锁,必须在unlock之后
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
for(int i=0;i<10;i++) {
executor.submit(comsumer);
}
executor.submit(producer);
}
public static void lock1() {
Lock lock = new ReentrantLock();
Runnable runnable = () -> {
System.out.println(Thread.currentThread().getId() + " enter");
while (true) {
lock.lock();
System.out.println(Thread.currentThread().getId() + " get lock");
try {
Thread.sleep(200L);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
System.out.println(Thread.currentThread().getId() + " exit ");
}
};
for (int i = 0; i < 100; i++) {
executor.execute(runnable);
}
}
public static void interrupt1() throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
Thread thread = Thread.currentThread();
while (!thread.isInterrupted()) {
System.out.println("thread running");
}
}
};
Thread rthread = new Thread(r);
rthread.start();
Thread.sleep(1000);
rthread.interrupt();
}
public static void interrupt2() throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
Thread thread = Thread.currentThread();
while (!Thread.interrupted()) {
System.out.println("thread running");
}
}
};
Thread rthread = new Thread(r);
rthread.start();
Thread.sleep(1000);
rthread.interrupt();
}
}