Java 之多线程

来源:互联网 发布:淘宝买东西剁手的说说 编辑:程序博客网 时间:2024/06/07 00:45

1.信号量:
Semaphore用于保存当前允许通过的线程数量
2.实例

public class Test {    public static void main(String[] args) throws Exception {        Test test = new Test();        for (int i = 0; i < 10; i++) {            new Thread(new Runnable() {                @Override                public void run() {                    try {                        test.print();                    } catch (Exception e) {                        e.printStackTrace();                    }                }            }).start();        }    }    Semaphore semaphore = new Semaphore(2);    private void print() throws Exception {        semaphore.acquire();        Thread.sleep(2000);        System.out.println(Thread.currentThread().getName() + " print...");        semaphore.release();    }}

3.总结:
Semaphore实现了线程锁的功能。