Monitor Directory and File(IV)Multi Threads

本文深入探讨了多线程编程中锁与无锁、Copy-On-Write ArrayList、CyclicBarrier与CountDownLatch等并发控制机制的应用实例。通过具体代码实现,展示了如何高效管理线程并确保数据一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值