`

线程的数量控制

阅读更多
在编程中,往往都需要采用线程来提高速度,但线程并不是越多越好。
1. 线程越多,JVM 所占资源越多
2. 线程越多,越容易造成资源冲突,如果处理不当,造成死锁。
所以,在启动线程的时候要根据应用程序的特点限制线程的数量。
本程序采用了java.util.concurrent的锁进行线程数量控制,测试代码如下:
/**
 * 专注互联网,分享创造价值
 *  maoxiang@gmail.com
 */
package cn.jteam.app.taobao.spider;
import java.net.InetAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
 *
 *  作用:
 */
public class TestThreadLock {
   
    private Lock lock = new ReentrantLock();
    final Condition full = lock.newCondition();
    final CountDownLatch startSignal = new CountDownLatch(1);
    private int threads;
    CountDownLatch signal = new CountDownLatch(5);
    public void addThreads() throws Exception {
        lock.lock();
        try {
            if (threads > 5) {
                full.await();
            }
            threads++;
        } finally {
            lock.unlock();
        }
    }
    public void removeThreads() {
        lock.lock();
        try {
            if (threads <= 5) {
                full.signal();
            }
            threads--;
        } finally {
            lock.unlock();
        }
    }
    /**
     * 测试线程
     * @throws Exception
     */
    public void run() throws Exception {
        for (int i = 0; i < 10; i++) {
            addThreads();
            final int j = i;
            (new Thread() {
                @Override
                public void run() {
                    try {
                        sleep(500);
                        System.out.println("current " + j + "=" + threads);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        removeThreads();
                        if (threads == 0) {
                            startSignal.countDown();
                        }
                    }
                }
            }).start();
        }
        startSignal.await();
    }
    public static void main0(String[] args) throws Exception {
        System.out.println("begin");
        TestThreadLock test = new TestThreadLock();
        test.run();
        System.out.println("end..........");
    }
     
}

输入结果为:
begin
current 1=6
current 0=6
current 5=5
current 3=4
current 4=4
current 2=4
current 7=4
current 6=3
current 8=3
current 9=3
end..........


这个程序里,限制了线程的数量为5,但线程超过5个时,就排队等待。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics