Monitor Directory and File(IV)Multi Threads
1. Lock - Free
simple lock and free
package com.xxxxxxx.importdata.filemonitor.multithreads;
import java.util.concurrent.atomic.AtomicInteger;
public class Counter
{
private AtomicInteger max = new AtomicInteger();
public void set(int value)
{
// step 1 loop
for (;;)
{
int current = max.get();
if (value > current)
{
// CAS compare and set
if (max.compareAndSet(current, value))
{
// break
break;
}
else
{
continue;
}
}
else
{
// break
break;
}
}
}
public int getMax()
{
return max.get();
}
}
Lock and Free in BeanManager
class BeanManager {
private ConcurrentMap<String, Object> map = new ConcurrentHashMap<String, Object>();
public Object getBean(String key) {
Object bean = map.get(key);
if (bean == null) {
map.putIfAbsent(key, createBean());
bean = map.get(key);
}
return bean;
}
}
CopyOnWriteArrayList
class Engine {
private List<Listener> listeners = new CopyOnWriteArrayList <Listener>();
public boolean addListener(Listener listener) {
return listeners.add(listener);
}
public void doXXX() {
for (Listener listener : listeners) {
listener.handle();
}
}
}
2. CoutDownLatch
Waiting for all the sub threads finished, the main thread continous.
package com.xxxxxx.importdata.filemonitor.multithreads;
import java.util.concurrent.CountDownLatch;
public class WaitingEndCoutDownLatchExecutor
{
public static void main(String[] args) throws InterruptedException
{
final int COUNT = 4;
final CountDownLatch completeLatch = new CountDownLatch(COUNT);
for (int i = 0; i < COUNT; ++i)
{
Thread thread = new Thread("worker thread " + i) {
public void run()
{
System.out.println("execute thread = " + Thread.currentThread().getName());
completeLatch.countDown();
}
};
thread.start();
}
completeLatch.await();
System.out.println("All threads finished!");
}
}
the result of console is:
execute thread = worker thread 0
execute thread = worker thread 2
execute thread = worker thread 1
execute thread = worker thread 3
All threads finished!
Start all the sub threads at the same time
package com.xxxxxx.importdata.filemonitor.multithreads;
import java.util.concurrent.CountDownLatch;
public class StartAfterSignalCoutDownLatchExecutor
{
public static void main(String[] args) throws InterruptedException
{
final CountDownLatch startLatch = new CountDownLatch(1);
for (int i = 0; i < 4; ++i)
{
Thread thread = new Thread("worker thread " + i) {
public void run()
{
try
{
startLatch.await();
}
catch (InterruptedException e)
{
return;
}
System.out.println("execute thread = " + Thread.currentThread().getName());
}
};
thread.start();
}
System.out.println("Let's start: ");
startLatch.countDown();
}
}
The result of the console is:
Let's begin:
execute thread = worker thread 0
execute thread = worker thread 2
execute thread = worker thread 1
execute thread = worker thread 3
3. CycliBarrier
When all the points reach, the system will go on.
package com.xxxxxx.importdata.filemonitor.multithreads;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CycliBarrierPerformanceRunner
{
private int threadCount;
private CyclicBarrier barrier;
private int loopCount = 2;
public CycliBarrierPerformanceRunner(int threadCount)
{
this.threadCount = threadCount;
barrier = new CyclicBarrier(threadCount, new Runnable() {
public void run()
{
collectTestResult();
}
});
for (int i = 0; i < threadCount; ++i)
{
Thread thread = new Thread("test-thread " + i) {
public void run()
{
for (int j = 0; j < loopCount; ++j)
{
doTest();
try
{
barrier.await();
}
catch (InterruptedException e)
{
return;
}
catch (BrokenBarrierException e)
{
return;
}
}
}
};
thread.start();
}
}
private void doTest()
{
System.out.println("executing thread = " + Thread.currentThread().getName());
}
private void collectTestResult()
{
System.out.println("Result thread = " + Thread.currentThread().getName());
}
public static void main(String[] args)
{
new CycliBarrierPerformanceRunner(3);
}
}
the result of the console is:
executing thread = test-thread 0
executing thread = test-thread 2
executing thread = test-thread 1
Result thread = test-thread 2
executing thread = test-thread 2
executing thread = test-thread 0
executing thread = test-thread 1
Result thread = test-thread 1
4. ScheduledExecutorService
schedule(Runnable command, long delay, TimeUnit unit) : ScheduledFuture
schedule(Callable<V> callable, long delay, TimeUnit unit) : ScheduledFuture
scheduleAtFixedRate(Runnable comand, long initDelay, long period, TimeUnit unit) : ScheduledFuture
scheduleWithFixedDelay(Runnable command, long initDelay, long delay, TimeUnit unit) : ScheduledFuture
package com.xxxxxxx.importdata.filemonitor.multithreads;
import java.util.TimerTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class ScheduledExecutorServiceRunner
{
public static void main(String[] args) throws InterruptedException, ExecutionException
{
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
SimpleTask task = new SimpleTask();
ScheduledFuture<?> future = scheduler.schedule(task, 1, TimeUnit.SECONDS);
// future.get();
// future.cancel(false);
scheduler.schedule(task, 2, TimeUnit.SECONDS);
scheduler.scheduleAtFixedRate(task, 2, 3, TimeUnit.SECONDS);
}
private static class SimpleTask extends TimerTask
{
public void run()
{
System.out.println("Task is running!");
}
}
}
references:
http://www.cnblogs.com/jobs
Monitor Directory and File(IV)Multi Threads
猜你喜欢
转载自sillycat.iteye.com/blog/1114480
今日推荐
周排行