자바 5.0 고성능 프로그램 개발 총화 (계속 보충)
24360 단어 자바
동기 화 된 집합 류
Hashtable
과 Vector
, 그리고 동기 화 된 포장 기 류 Collections.synchronizedMap
과 Collections.synchronizedList
은 Map
과 List
에 기본 적 인 조건 부 스 레 드 안전 실현 을 제공 했다.그러나 일부 요소 로 인해 고도 의 동시성 을 가 진 응용 프로그램 에 적용 되 지 않 는 다. 그들의 집합 범위 의 단일 잠 금 특성 은 신축성 에 있어 장애 가 되 고 ConcurrentModificationException
s 이상 이 발생 하지 않도록 비교적 긴 시간 안에 집합 을 잠 가 야 하 는 경우 가 많다.ConcurrentHashMap
과 CopyOnWriteArrayList
은 더욱 높 은 동시성 을 제공 하 는 동시에 스 레 드 안전성 도 지 켰 으 며 호출 자의 약속 에 대해 약간의 할인 을 했 을 뿐이다.ConcurrentHashMap
과 CopyOnWriteArrayList
은 귀하 가 HashMap
또는 ArrayList
을 사용 하 는 어느 곳 에서 든 반드시 유용 한 것 이 아니 라 특정한 공공 해결 방안 을 최적화 시 키 는 디자인 입 니 다.많은 병렬 응용 프로그램 이 그들의 사용 에서 이익 을 얻 을 것 이다.요약: 다 중 스 레 드 병발 상황 에서
ConcurrentModificationException
s 이상 을 피하 기 위해 ConcurrentHashMap
과 CopyOnWriteArrayList
。
을 사용 하 는 것 을 권장 합 니 다. :ConcurrentLinkedQueue、CopyOnWriteArraySet、LinkedBlockingQueue、ArrayBlockingQueue
、
, , :
A*2=a<<1
A/2=a>>1
。
、
,
AtomicInteger
( ),
Integer 。 ,
Number
, 。
예 를 들 면:
private AtomicInteger bomdIdCreator = new AtomicInteger(); //셀 프 시리 얼 번호
/**
*새로운 ID 를 받 아 자체 증가 유지
*@return
*/
public int getNewBombID(){
return bomdIdCreator.addAndGet(1);
}
、
, , 。 :
1.
、 :
synchronized
2.
:(
wait 、
notify
notifyAll )
3. ReentrantLock
:ReentrantLock
Lock ,
synchronized
, 。
: ,
lock
try
,
/
, :
class X {
private final ReentrantLock lock = new ReentrantLock();
// ...
public void m() {
lock.lock(); // block until condition holds
try {
// ... method body
} finally {
lock.unlock()
}
}
}
、
Doug Lea
util.concurrent
, 、 、 。
ThreadPoolExecutor
、 。 , ,
util.concurrent
。
: , , ( ) 。
Executors
Executors.newCachedThreadPool() ( , )、
Executors.newFixedThreadPool(int) ( )
Executors.newSingleThreadExecutor() ( ), 。
:
public class ThreadPoolExecutorTest {
final static ExecutorService threadPool = Executors. newCachedThreadPool (); / 간단 한 스 레 드 풀 구현
/**
* @param args
*/
public static void main(String[] args) {
for(int i=0;i<10;i++){
threadPool.execute(new Runnable(){
public void run() {
System.out.println("aaa"+this.getClass().getName());
//do other things
}
});
}
}
}
、
1.
Timer
2. ScheduledThreadPoolExecutor
(
JDK 1.5
)
3. Quatz
Java 5.0
,
java.util.concurrent
ScheduledThreadPoolExecutor
, ,
Timer
。
ScheduledThreadPoolExecutor
scheduleAtFixedRate()
scheduleWithFixedDelay()
,
Timer
scheduleWithFixedDelay()
。
:
ScheduledThreadPoolExecutor
ScheduledExecutorService
。
1)public static final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(2);
2)public static final ScheduledThreadPoolExecutor scheduledExecutor=new ScheduledThreadPoolExecutor(2);
, 。
ScheduledThreadPoolExecutor
Timer
:
1.
Timer
:
//
void schedule(TimerTask task, Date time)
//
void schedule(TimerTask task, Date firstTime, long period)
//
void schedule(TimerTask task, long delay)
//
void schedule(TimerTask task, long delay, long period)
//
void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
//
void scheduleAtFixedRate(TimerTask task, long delay, long period)
:
,
period
;
scheduleAtFixedRate
period
。 ,
schedule()
,
scheduleAtFixedRate()
, 。
2.
ScheduledThreadPoolExecutor
:
//
<V>ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit)
//
ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit)
//
(
Timer.scheduleAtFixedRate())
ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
//
(
Timer.schedule())
ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
:
(
1
)
Timer
, ;
ScheduledThreadPoolExecutor
。
(
2
)
Timer
TimerTask
,
TimerTask
TimerTask
;
ScheduledThreadPoolExecutor
。
(
3
)
Timer
TimerTask
, ,
Timer
,
TimerTask
,
TimerTask
;
ScheduledThreadPoolExecutor
, 。
:
Timer
,
JDK1.5
,
Timer
。
( : , : ,http://www.blogjava.net/hankchen)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.