- 浏览: 2542825 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
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
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
发表评论
-
Stop Update Here
2020-04-28 09:00 310I will stop update here, and mo ... -
NodeJS12 and Zlib
2020-04-01 07:44 468NodeJS12 and Zlib It works as ... -
Docker Swarm 2020(2)Docker Swarm and Portainer
2020-03-31 23:18 362Docker Swarm 2020(2)Docker Swar ... -
Docker Swarm 2020(1)Simply Install and Use Swarm
2020-03-31 07:58 364Docker Swarm 2020(1)Simply Inst ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 330Traefik 2020(1)Introduction and ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 424Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 428Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 367Docker Compose 2020(1)Installat ... -
VPN Server 2020(2)Docker on CentOS in Ubuntu
2020-03-02 08:04 445VPN Server 2020(2)Docker on Cen ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 377Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 468NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 414Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 332Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 243GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 445GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 321GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 307Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 310Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 286Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 303Serverless with NodeJS and Tenc ...
相关推荐
Threads and the Concurrency Utilities helps all Java developers master and use these capabilities effectively. This book is divided into two parts of four chapters each. Part 1 focuses on the Thread...
sdk2003文档 DLLs, Processes, and Threads
标题 "IBM Theard and Monitor" 暗示我们讨论的主题是IBM的一款用于监控线程(Threads)和系统资源的工具,可能与Java应用程序性能优化有关。描述中提到的"javacore分析软件"通常指的是当Java应用遇到问题,如内存...
### 多线程编程指南(POSIX与Solaris线程) #### 概述 本指南主要介绍了POSIX(便携式操作系统接口)和Solaris环境下多线程编程的基础概念、核心原理及其应用实践。该指南共计387页,详细阐述了在POSIX标准下进行...
Unix Systems Programming Communication, Concurrency, and Threads 2003.chm
A self-contained reference that relies on the latest UNIX standards,UNIX Systems Programming provides thorough coverage of files, signals,semaphores, POSIX threads, and client-server communication....
4. **监视器(Monitor)**: 监视器是一种线程同步机制,通常由一个互斥锁和一组条件变量组成。它允许多个线程进入同一块代码区域,但一次只有一个线程可以执行,其他线程必须等待条件满足才能继续,如Java中的`...
"Thread-work-with-txt-file.rar_threads_txt"这个压缩包文件似乎包含了一个关于如何在文本文件操作中使用线程的示例或教程。 描述中的“Synchronize content 2 files using threads”提示我们,这个项目可能涉及到...
本示例"3_threads_write_file.rar"是关于在Linux下如何使用线程进行文件写入操作的一个综合实例。这个例子将帮助你深入理解和掌握线程在实际编程中的应用。 首先,我们要了解Linux下的线程API,它主要基于POSIX标准...
赠送jar包:jboss-threads-3.1.0.Final.jar; 赠送原API文档:jboss-threads-3.1.0.Final-javadoc.jar; 赠送源代码:jboss-threads-3.1.0.Final-sources.jar; 赠送Maven依赖信息文件:jboss-threads-3.1.0.Final....
Threads and the Concurrency Utilities helps all Java developers master and use these capabilities effectively. This book is divided into two parts of four chapters each. Part 1 focuses on the Thread...
This fully updated UNIX classic covers everything students need to know to master UNIX threads, TCP/IP, and RPC programming—with reusable code examples that explain syntax every step of the way....
Oracle Solaris 9 操作系统 Threads and Realtime Library 函数手册 Oracle Solaris 9 操作系统是由 Sun Microsystems 公司开发的 Unix 操作系统之一。该操作系统主要面向服务器端市场,具有高度的稳定性、安全性...
In shared memory multiprocessor architectures, such as SMPs, threads can be used to implement parallelism. Historically, hardware vendors have implemented their own proprietary versions of threads, ...
Oracle Solaris 9 -man pages section 3:Threads and Realtime Library Functions Oracle Solaris 9 是一个基于 Unix 的操作系统,由 Sun Microsystems 开发。man pages section 3 documentation 中的 Threads and ...
《Java多线程与并发工具》一书深入讲解了Java中线程API和并发工具的使用,这些内容是Java语言中最强大但也最具挑战性的API和语言特性之一。对于初学者而言,利用这些特性编写正确的多线程应用程序通常是非常困难的。...
The `/proc` directory contains information about running processes and system statistics. This appendix covers: - **Process Information**: Retrieving details about running processes. - **System ...
Multicore Programming on Linux , posix and openmp threads