package com.zhi;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.time.LocalDateTime;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Created by xukezhi on 17/9/15.
*/
@RunWith(JUnit4.class)
public class ThreadTest {
private static volatile long testCount=200;
private static AtomicInteger atomicInteger = new AtomicInteger(200);
public static class WorkerThread implements Runnable{
CyclicBarrier barrier;
public WorkerThread(CyclicBarrier b){
this.barrier = b;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
barrier.await();
int i = atomicInteger.get();
atomicInteger.compareAndSet(i,++i);
}catch(Exception e){
e.printStackTrace();
}
}
}
public static class lockThread implements Runnable{
Object barrier;
public lockThread(Object b){
this.barrier = b;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
synchronized (barrier){
System.out.println(Thread.currentThread()+"hold loc notify@"+ LocalDateTime.now());
testCount--;
barrier.notifyAll();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public static class waitThread implements Runnable{
Object barrier;
public waitThread(Object b){
this.barrier = b;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
synchronized (barrier){
while (testCount==200){
System.out.println(Thread.currentThread()+"wai testCount is "+testCount);
barrier.wait();
System.out.println(Thread.currentThread()+"haha is new "+testCount);
Thread.sleep(200);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
@Test
public void test(){
Object info = new Object();
lockThread thread1 = new lockThread(info);
waitThread thread2 = new waitThread(info);
waitThread thread3 = new waitThread(info);
waitThread thread4 = new waitThread(info);
waitThread thread5 = new waitThread(info);
ThreadPoolExecutor executor = new ThreadPoolExecutor(100,150,30, TimeUnit.MINUTES,new ArrayBlockingQueue<Runnable>(130));
executor.execute(thread2);
executor.execute(thread3);
executor.execute(thread4);
executor.execute(thread5);
executor.execute(thread1);
// for(int i=0;i<99;i++){
// executor.execute(new Thread(thread,String.valueOf(i)));
//
// }
// try {
// cb.await();
// } catch (Exception e) {
// e.printStackTrace();
// }
System.out.println("atomicInteger"+atomicInteger.get());
executor.shutdown();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}