`

Concurrent - Semaphore - acquireUninterruptibly()

 
阅读更多

原创转载请注明出处:http://agilestyle.iteye.com/blog/2342923

 

acquireUninterruptibly()作用是使等待进入acquire()方法的线程,不允许被中断。

acquireUninterruptibly()还有重载的方法acquireUninterruptibly(int permits),此方法的作用是在等待permits的情况下不允许被中断,如果成功获得锁,则取得指定permits的个数。

 

Service.java 

package org.fool.java.concurrent.semaphore.acquireuninterruptibly;

import java.util.concurrent.Semaphore;

public class Service {
    private Semaphore semaphore = new Semaphore(1);

    public void testMethod() {
        try {
            semaphore.acquire();

            System.out.println(Thread.currentThread().getName() + " begin timer=" + System.currentTimeMillis());

            for(int i = 0; i < Integer.MAX_VALUE / 50; i++) {
                new String();
                Math.random();
            }

            System.out.println(Thread.currentThread().getName() + " end timer=" + System.currentTimeMillis());

            semaphore.release();
        } catch (Exception e) {
            System.out.println(Thread.currentThread().getName() + " in catch...");
            e.printStackTrace();
        }
    }
}

ThreadA.java

package org.fool.java.concurrent.semaphore.acquireuninterruptibly;

public class ThreadA implements Runnable {
    private Service service;

    public ThreadA(Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.testMethod();
    }
}

ThreadB.java

package org.fool.java.concurrent.semaphore.acquireuninterruptibly;

public class ThreadB implements Runnable {
    private Service service;

    public ThreadB(Service service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.testMethod();
    }
}

SemaphoreTest.java

package org.fool.java.concurrent.semaphore.acquireuninterruptibly;

public class SemaphoreTest {
    public static void main(String[] args) throws InterruptedException {
        Service service = new Service();

        Thread a = new Thread(new ThreadA(service));
        a.setName("A");
        a.start();

        Thread b = new Thread(new ThreadB(service));
        b.setName("B");
        b.start();

        Thread.sleep(1000);

        b.interrupt();
    }
}

Run


Note:

线程B被成功中断。

 

修改Service.java,将

semaphore.acquire();

改为

semaphore.acquireUninterruptibly();

再Run


Note:

线程B没有被中断。

 

 

 

 

 

 

 

 

 

  • 大小: 11.6 KB
  • 大小: 25.4 KB
  • 大小: 15.5 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics