Java 阻塞线程用法

CountDownLatch

首先先说明CountDownLatch辅助类

CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
主要方法
public CountDownLatch(int count);//构造方法参数指定了计数的次数
public void countDown();//当前线程调用此方法,则计数减一1
public void await() throws InterruptedException//调用此方法会一直阻塞当前线程,直到计时器的值为0
列子:

public class CountDownLatchDemo {
    final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch=new CountDownLatch(2);//两个工人的协作
        Worker worker1=new Worker("zhang san", 5000, latch);
        Worker worker2=new Worker("li si", 8000, latch);
        worker1.start();//
        worker2.start();//
        latch.await();//等待所有工人完成工作
        System.out.println("all work done at "+sdf.format(new Date()));
    }


    static class Worker extends Thread{
        String workerName; 
        int workTime;
        CountDownLatch latch;
        public Worker(String workerName ,int workTime ,CountDownLatch latch){
             this.workerName=workerName;
             this.workTime=workTime;
             this.latch=latch;
        }
        public void run(){
            System.out.println("Worker "+workerName+" do work begin at "+sdf.format(new Date()));
            doWork();//工作了
            System.out.println("Worker "+workerName+" do work complete at "+sdf.format(new Date()));
            latch.countDown();//工人完成工作,计数器减一

        }

        private void doWork(){
            try {
                Thread.sleep(workTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}


输出:
Worker zhang san do work begin at 2011-04-14 11:05:11
Worker li si do work begin at 2011-04-14 11:05:11
Worker zhang san do work complete at 2011-04-14 11:05:16
Worker li si do work complete at 2011-04-14 11:05:19
all work done at 2011-04-14 11:05:19

并发队列ConcurrentLinkedQueue和阻塞队列LinkedBlockingQueue用法

在Java多线程应用中,队列的使用率很高,多数生产消费模型的首选数据结构就是队列(先进先出)。Java提供的线程安全的Queue可以分为阻塞队列和非阻塞队列,其中阻塞队列的典型例子是BlockingQueue,非阻塞队列的典型例子是ConcurrentLinkedQueue,在实际应用中要根据实际需要选用阻塞队列或者非阻塞队列。

注:什么叫线程安全?这个首先要明确。线程安全就是说多线程访问同一代码,不会产生不确定的结果。

并行和并发区别

1、并行是指两者同时执行一件事,比如赛跑,两个人都在不停的往前跑;
2、并发是指资源有限的情况下,两者交替轮流使用资源,比如一段路(单核CPU资源)同时只能过一个人,A走一段后,让给B,B用完继续给A ,交替使用,目的是提高效率

LinkedBlockingQueue
由于LinkedBlockingQueue实现是线程安全的,实现了先进先出等特性,是作为生产者消费者的首选,LinkedBlockingQueue 可以指定容量,也可以不指定,不指定的话,默认最大是Integer.MAX_VALUE,其中主要用到put和take方法,put方法在队列满的时候会阻塞直到有队列成员被消费,take方法在队列空的时候会阻塞,直到有队列成员被放进来。

package cn.thread;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 多线程模拟实现生产者/消费者模型
 *  
 * @author 林计钦
 * @version 1.0 2013-7-25 下午05:23:11
 */
public class BlockingQueueTest2 {
    /**
     * 
     * 定义装苹果的篮子
     * 
     */
    public class Basket {
        // 篮子,能够容纳3个苹果
        BlockingQueue<String> basket = new LinkedBlockingQueue<String>(3);

        // 生产苹果,放入篮子
        public void produce() throws InterruptedException {
            // put方法放入一个苹果,若basket满了,等到basket有位置
            basket.put("An apple");
        }

        // 消费苹果,从篮子中取走
        public String consume() throws InterruptedException {
            // take方法取出一个苹果,若basket为空,等到basket有苹果为止(获取并移除此队列的头部)
            return basket.take();
        }
    }

    // 定义苹果生产者
    class Producer implements Runnable {
        private String instance;
        private Basket basket;

        public Producer(String instance, Basket basket) {
            this.instance = instance;
            this.basket = basket;
        }

        public void run() {
            try {
                while (true) {
                    // 生产苹果
                    System.out.println("生产者准备生产苹果:" + instance);
                    basket.produce();
                    System.out.println("!生产者生产苹果完毕:" + instance);
                    // 休眠300ms
                    Thread.sleep(300);
                }
            } catch (InterruptedException ex) {
                System.out.println("Producer Interrupted");
            }
        }
    }

    // 定义苹果消费者
    class Consumer implements Runnable {
        private String instance;
        private Basket basket;

        public Consumer(String instance, Basket basket) {
            this.instance = instance;
            this.basket = basket;
        }

        public void run() {
            try {
                while (true) {
                    // 消费苹果
                    System.out.println("消费者准备消费苹果:" + instance);
                    System.out.println(basket.consume());
                    System.out.println("!消费者消费苹果完毕:" + instance);
                    // 休眠1000ms
                    Thread.sleep(1000);
                }
            } catch (InterruptedException ex) {
                System.out.println("Consumer Interrupted");
            }
        }
    }

    public static void main(String[] args) {
        BlockingQueueTest2 test = new BlockingQueueTest2();

        // 建立一个装苹果的篮子
        Basket basket = test.new Basket();

        ExecutorService service = Executors.newCachedThreadPool();
        Producer producer = test.new Producer("生产者001", basket);
        Producer producer2 = test.new Producer("生产者002", basket);
        Consumer consumer = test.new Consumer("消费者001", basket);
        service.submit(producer);
        service.submit(producer2);
        service.submit(consumer);
        // 程序运行5s后,所有任务停止
//        try {
//            Thread.sleep(1000 * 5);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        service.shutdownNow();
    }

}

ConcurrentLinkedQueue
ConcurrentLinkedQueue是Queue的一个安全实现.Queue中元素按FIFO原则进行排序.采用CAS操作,来保证元素的一致性。
LinkedBlockingQueue是一个线程安全的阻塞队列,它实现了BlockingQueue接口,BlockingQueue接口继承自java.util.Queue接口,并在这个接口的基础上增加了take和put方法,这两个方法正是队列操作的阻塞版本。

package cn.thread;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentLinkedQueueTest {
    private static ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<Integer>();
    private static int count = 2; // 线程个数
    //CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
    private static CountDownLatch latch = new CountDownLatch(count);

    public static void main(String[] args) throws InterruptedException {
        long timeStart = System.currentTimeMillis();
        ExecutorService es = Executors.newFixedThreadPool(4);
        ConcurrentLinkedQueueTest.offer();
        for (int i = 0; i < count; i++) {
            es.submit(new Poll());
        }
        latch.await(); //使得主线程(main)阻塞直到latch.countDown()为零才继续执行
        System.out.println("cost time " + (System.currentTimeMillis() - timeStart) + "ms");
        es.shutdown();
    }

    /**
     * 生产
     */
    public static void offer() {
        for (int i = 0; i < 100000; i++) {
            queue.offer(i);
        }
    }


    /**
     * 消费
     *  
     * @author 林计钦
     * @version 1.0 2013-7-25 下午05:32:56
     */
    static class Poll implements Runnable {
        public void run() {
            // while (queue.size()>0) {
            while (!queue.isEmpty()) {
                System.out.println(queue.poll());
            }
            latch.countDown();
        }
    }
}

运行结果:
costtime 2360ms

改用while (queue.size()>0)后
运行结果:
cost time 46422ms

结果居然相差那么大,看了下ConcurrentLinkedQueue的API原来.size()是要遍历一遍集合的,难怪那么慢,所以尽量要避免用size而改用isEmpty().

### Java 实现线程阻塞的方法 在 Java 中,线程阻塞通常通过 `Object.wait()` 方法或使用同步工具类(如 `Lock` 和 `Condition`)来实现。以下是几种常见的实现方式及其示例代码。 #### 1. 使用 `Object.wait()` 和 `notify()` 当一个线程调用了对象的 `wait()` 方法时,它会被挂起并释放该对象上的锁,直到另一个线程对该对象调用 `notify()` 或 `notifyAll()` 方法为止。 ```java public class WaitNotifyExample { private static final Object lock = new Object(); public static void main(String[] args) throws InterruptedException { Thread waiter = new Thread(() -> { synchronized (lock) { try { System.out.println("Waiting..."); lock.wait(); // 线程在此处阻塞 System.out.println("Notified!"); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread notifier = new Thread(() -> { try { Thread.sleep(2000); // 让等待线程先启动 } catch (InterruptedException e) { e.printStackTrace(); } synchronized (lock) { System.out.println("Notifying..."); lock.notify(); // 唤醒等待线程 } }); waiter.start(); notifier.start(); waiter.join(); // 等待等待线程结束 notifier.join(); // 等待通知线程结束 } } ``` 上述代码展示了如何利用 `wait()` 和 `notify()` 来实现线程间的协作[^2]。 --- #### 2. 使用 `Thread.sleep(long millis)` `Thread.sleep(millis)` 是一种简单的阻塞机制,可以让当前线程暂停指定的时间毫秒数,在这段时间内不会占用 CPU 时间片。 ```java public class SleepExample { public static void main(String[] args) { Thread sleeper = new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println("Sleeping... " + i); try { Thread.sleep(1000); // 当前线程休眠1秒钟 } catch (InterruptedException e) { e.printStackTrace(); } } }); sleeper.start(); } } ``` 此方法适用于需要延迟执行某些操作的情况[^3]。 --- #### 3. 使用 `BlockingQueue` 的阻塞特性 Java 提供了多种阻塞队列(如 `LinkedBlockingQueue`),这些队列在其核心方法(如 `put()` 和 `take()`)中实现了天然的阻塞行为。 ```java import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class BlockingQueueExample { public static void main(String[] args) { BlockingQueue<String> queue = new LinkedBlockingQueue<>(1); Thread producer = new Thread(() -> { try { for (int i = 1; i <= 5; i++) { queue.put(i + ""); // 如果队列已满,则阻塞 System.out.println("Produced: " + i); } } catch (InterruptedException e) { e.printStackTrace(); } }); Thread consumer = new Thread(() -> { try { for (int i = 1; i <= 5; i++) { String item = queue.take(); // 如果队列为空,则阻塞 System.out.println("Consumed: " + item); } } catch (InterruptedException e) { e.printStackTrace(); } }); producer.start(); consumer.start(); } } ``` 这段代码演示了生产者-消费者模式下的自然阻塞行为[^4]。 --- #### 4. 使用 `ReentrantLock` 和 `Condition` 更高级的方式是通过显式的锁和条件变量来控制线程阻塞与唤醒。 ```java import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockAndConditionExample { private static final Lock lock = new ReentrantLock(); private static final Condition condition = lock.newCondition(); private static boolean ready = false; public static void main(String[] args) { Thread waitingThread = new Thread(() -> { lock.lock(); try { while (!ready) { System.out.println("Waiting for signal..."); condition.await(); // 阻塞当前线程 } System.out.println("Signal received! Ready is now true."); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } }); Thread signalingThread = new Thread(() -> { lock.lock(); try { System.out.println("Setting ready to true and signaling..."); ready = true; condition.signal(); // 唤醒等待线程 } finally { lock.unlock(); } }); waitingThread.start(); signalingThread.start(); } } ``` 这种方式提供了更高的灵活性和可控性[^5]。 --- ### 结论 以上介绍了四种不同的线程阻塞实现方式:基于 `wait()` 和 `notify()`、`Thread.sleep()`、`BlockingQueue` 自然阻塞以及 `ReentrantLock` 和 `Condition` 显式锁定。每种方式都有其适用场景,开发者应根据实际需求选择合适的方案。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值