JUC笔记(使用)
三、使用
线程创建和使用
@Test
public void test04(){
ExecutorService service = new ThreadPoolExecutor(
2,
Runtime.getRuntime().availableProcessors(),
2,
TimeUnit.SECONDS,
new LinkedBlockingDeque<>(3)
);
for (int i = 0; i < 10; i++) {
service.submit(()->{
System.out.println(Thread.currentThread().getName());
});
}
service.shutdown();
}
@Test
public void test03() throws ExecutionException, InterruptedException {
class Test03 implements Callable<String> {
@Override
public String call() {
return "1";
}
}
Test03 test03 = new Test03();
FutureTask<String> ft=new FutureTask<>(test03);
Thread t=new Thread(ft);
t.start();
System.out.println(ft.get());
}
@Test
public void test02(){
class Test02 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("执行了run方法");
}
}
}
new Thread(new Test02()).start();
}
@Test
public void test01(){
class Test01 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("执行了run方法");
}
}
}
new Test01().start();
}
volatile关键字的使用
public class Demo01 {
private static volatile int num = 0;
AtomicInteger atomicInteger = new AtomicInteger(0);
@Test
public void test02(){
for (int i = 0; i < 10; i++) {
new Thread(()->num++).start();
}
System.out.println(num);
for (int i = 0; i < 10; i++) {
new Thread(()->atomicInteger.getAndIncrement()).start();
}
while (Thread.activeCount()>2){
Thread.yield();
}
System.out.println(atomicInteger.get());
}
@Test
public void test01(){
new Thread(()-> {while(num == 0){}}).start();
num++;
System.out.println(num);
}
}
Lock锁的使用
public class Demo01 {
public static void main(String[] args){
ProductionAndConsumption pac = new ProductionAndConsumption();
for (int i = 0; i < 10; i++) {
new Thread(()->pac.getNumber()).start();
}
for (int i = 10; i < 20; i++) {
new Thread(()->pac.setNumber()).start();
}
}
}
class ProductionAndConsumption{
private int number = 0;
public Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void setNumber(){
lock.lock();
try{
while (number == 1){
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.printf(Thread.currentThread().getName()+"\t生产\t库存: %s\n",++number);
condition.signalAll();
}catch(Exception e){
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void getNumber(){
lock.lock();
try{
while (number == 0){
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.printf(Thread.currentThread().getName()+"\t消费\t\t库存: %s\n",--number);
condition.signalAll();
}catch(Exception e){
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
ForkJoin的使用
public class SumTask extends RecursiveTask<Long> {
public static void main(String[] args){
long[] array = new long[400];
for (int i = 0; i < array.length; i++) {
array[i] = new Random().nextInt(1000);
}
ForkJoinPool fjp = new ForkJoinPool(4);
ForkJoinTask<Long> task = new SumTask(array, 0, array.length);
long startTime = System.currentTimeMillis();
Long result = fjp.invoke(task);
long endTime = System.currentTimeMillis();
System.out.println("Fork/join sum: " + result + " in " + (endTime - startTime) + " ms.");
}
static final int THRESHOLD = 100;
long[] array;
int start;
int end;
SumTask(long[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
if (end - start <= THRESHOLD) {
long sum = 0;
for (int i = start; i < end; i++) {
sum += array[i];
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(String.format("compute %d~%d = %d", start, end, sum));
return sum;
}
int middle = (end + start) / 2;
System.out.println(String.format("split %d~%d ==> %d~%d, %d~%d", start, end, start, middle, middle, end));
SumTask subtask1 = new SumTask(this.array, start, middle);
SumTask subtask2 = new SumTask(this.array, middle, end);
invokeAll(subtask1, subtask2);
Long subresult1 = subtask1.join();
Long subresult2 = subtask2.join();
Long result = subresult1 + subresult2;
System.out.println("result = " + subresult1 + " + " + subresult2 + " ==> " + result);
return result;
}
}