Several API in Java and contracting

And contracting

(Counter) CountDownLatch

CountDownLatchClass located in java.util.concurrentthe package, which may be implemented using functionally similar counter. For example, there is a task A, it wants to wait for other 4tasks to perform after completion to perform, then you can use CountDownLatchto achieve this functionality a. CountDownLatchIt is accomplished by a number of the counter, the initial value of the thread counter. Whenever a thread after the completion of its mandate, the counter value will be reduced 1. When the counter reaches the value 0, it means that all the threads have completed the task, and then wait for the thread locking can be restored on a mission.

import java.util.concurrent.CountDownLatch;
public class CountDownlatchTest {
    public static void main(String[] args) {
        CountDownLatch count = new CountDownLatch(2);
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "开始执行-->" + System.currentTimeMillis());
                count.countDown();
                System.out.println(Thread.currentThread().getName() + "结束执行-->" + System.currentTimeMillis());
            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "开始执行-->" + System.currentTimeMillis());
                count.countDown();
                System.out.println(Thread.currentThread().getName() + "结束执行-->" + System.currentTimeMillis());
            }
        }).start();

        try {
            count.await(); // 当Count减为0 时,执行后面的代码
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("两个子线程执行完毕....");
        System.out.println("主线程继续执行.....");
        for (int i = 0; i < 10; i++) {
            System.out.println("main,i:" + i);
        }
    }
}

Results of the

Thread-0开始执行-->1564281731639
Thread-0结束执行-->1564281731639
Thread-1开始执行-->1564281731639
Thread-1结束执行-->1564281731639
两个子线程执行完毕....
主线程继续执行.....
main,i:0
main,i:1
main,i:2
main,i:3
main,i:4
main,i:5
main,i:6
main,i:7
main,i:8
main,i:9

(Barrier) CyclicBarrier

  CyclicBarrierWhen initializing a specified number, then calculate the call CyclicBarrier.await()number of threads waiting to enter. When the number of threads reached this number, all the threads into a wait state wakes up and continues.
  CyclicBarrierLike its name means the same, it can be seen as an obstacle to be in attendance after all the threads together through this barrier.
  CyclicBarrierInitially with an optional Runnableparameter, this Runnabletask CyclicBarrierafter the number reached, all other threads to be executed before being awakened.

import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
        for (int i = 0; i < 5; i++) {
            Writer writer = new Writer(cyclicBarrier);
            writer.start();
        }
    }
}

class Writer extends Thread {
    private CyclicBarrier cyc;

    public Writer(CyclicBarrier cyc) {
        this.cyc = cyc;
    }

    @Override
    public void run() {
        System.out.println("线程" + Thread.currentThread().getName() + ",正在写入数据");
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            // TODO: handle exception
        }
        System.out.println("线程" + Thread.currentThread().getName() + ",写入数据成功.....");
        try {
            cyc.await();
        } catch (Exception e) {
        }
        System.out.println("所有线程执行完毕..........");
    }
}

Results of the

线程Thread-0,正在写入数据
线程Thread-2,正在写入数据
线程Thread-1,正在写入数据
线程Thread-3,正在写入数据
线程Thread-4,正在写入数据
线程Thread-3,写入数据成功.....
线程Thread-1,写入数据成功.....
线程Thread-0,写入数据成功.....
线程Thread-2,写入数据成功.....
线程Thread-4,写入数据成功.....
所有线程执行完毕..........
所有线程执行完毕..........
所有线程执行完毕..........
所有线程执行完毕..........
所有线程执行完毕..........

(Counting semaphores) Semaphore

  SemaphoreIt based on a counting semaphore. It can set a threshold value, based on this, the signal multiple threads compete to obtain a license to do after their application for restitution, after exceeding the threshold value, the thread will apply for permission signal is blocked. 
   SemaphorePooling can be used to construct a number of resource pools and the like, such as a database connection pool, we can create a count 1of Semaphore, as a similar mechanism for the mutex, which is also called binary flag amount , expressed two mutually denounced the state . It is used as follows:

semp.availablePermits()//函数用来获取当前可用的资源数量
semp.acquire(); //申请资源
semp.release();// 释放资源
// 创建一个计数阈值为5的信号量对象  
// 只能5个线程同时访问  
Semaphore semp = new Semaphore(5);  
try {  
  // 申请许可  
  semp.acquire();  
  try {  
    // 业务逻辑  
  }catch (Exception e){  
  } finally {  
    // 释放许可  
    semp.release();  
  }  
}catch(InterruptedException e){ }  

Case:

demand:

  A store only three crane machines, but 10 people came to the doll, then how do? Suppose the number of people 10 to 10, respectively, and first to No. 1, No. 10 and finally to. Then came the inevitable 1-3 available crane machines, can begin to grasp the doll, No. 4 came in front of three people need to see if anyone caught over, if someone caught End, No. 4 began to grasp the baby, or wait . By the same token, also we need to wait for 4-10 people are caught doll grip finish to catch, and who first began to grasp the doll waiting to see whether the person has a quality, if you can abide by the rules first come, first by grasping play machine.

Code:

import java.util.Random;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {
    public static void main(String[] args) {
        Semaphore semp = new Semaphore(3);
        for (int i = 0; i <= 10; i++) {
            CatchDollThread thread = new CatchDollThread("thread-" + i, semp);
            thread.start();
        }
    }
}

class CatchDollThread extends Thread {
    private String name;
    private Semaphore cad;
    public CatchDollThread(String name, Semaphore cad) {
        this.name = name;
        this.cad = cad;
    }

    @Override
    public void run() {
        int availablePermits = cad.availablePermits();
        if (availablePermits > 0) {
            System.out.println(this.name + "说: 有空闲的抓娃娃机");
        } else {
            System.out.println(this.name + "说: 没有空闲的娃娃机了");
        }
        try {
            // 申请资源
            cad.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(this.name + "开始抓娃娃" + ",此时空闲的机器:" + cad.availablePermits());
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (Exception e) {
        }
        System.out.println(this.name + "抓完娃娃");
        // 释放资源
        cad.release();

    }
}

Results of the

thread-1说: 有空闲的抓娃娃机
thread-3说: 有空闲的抓娃娃机
thread-2说: 有空闲的抓娃娃机
thread-0说: 有空闲的抓娃娃机
thread-4说: 没有空闲的娃娃机了
thread-2开始抓娃娃,此时空闲的机器:0
thread-3开始抓娃娃,此时空闲的机器:1
thread-1开始抓娃娃,此时空闲的机器:2
thread-5说: 没有空闲的娃娃机了
thread-6说: 没有空闲的娃娃机了
thread-7说: 没有空闲的娃娃机了
thread-8说: 没有空闲的娃娃机了
thread-9说: 没有空闲的娃娃机了
thread-10说: 没有空闲的娃娃机了
thread-1抓完娃娃
thread-0开始抓娃娃,此时空闲的机器:0
thread-3抓完娃娃
thread-4开始抓娃娃,此时空闲的机器:0
thread-4抓完娃娃
thread-5开始抓娃娃,此时空闲的机器:0
thread-0抓完娃娃
thread-6开始抓娃娃,此时空闲的机器:0
thread-2抓完娃娃
thread-7开始抓娃娃,此时空闲的机器:0
thread-6抓完娃娃
thread-8开始抓娃娃,此时空闲的机器:0
thread-5抓完娃娃
thread-9开始抓娃娃,此时空闲的机器:0
thread-8抓完娃娃
thread-10开始抓娃娃,此时空闲的机器:0
thread-10抓完娃娃
thread-7抓完娃娃
thread-9抓完娃娃

Guess you like

Origin www.cnblogs.com/haoworld/p/tb004bing-fa-bian-chengbing-fa-bao-xia-de-ji-geapi.html