├── concurrent.pptx ├── .gitignore ├── src └── main │ └── java │ └── com │ └── shawn │ └── concurrent │ └── demo │ ├── atomic │ ├── AtomicInteger.java │ └── AtomicIntegerWithLock.java │ ├── basic │ ├── InterruptDemo.java │ ├── ThreadWithReturnValue.java │ ├── ThreadInitExample.java │ ├── SyncBankAccount.java │ ├── ReentrantLockTest.java │ ├── BasicThreadTest.java │ └── BackwardThread.java │ ├── util │ ├── PrintQueueWithSemaphore.java │ ├── CountDownLatchDemo.java │ ├── PrintQueueWithReentrantLock.java │ ├── PriceInfoWithReadWriteLockDemo.java │ ├── ExchangeDataInConTask.java │ ├── PrintQueueWithMultiRecSemaphore.java │ ├── ExecutorServer.java │ ├── CountNumberByCyclicBarrier.java │ ├── SyncTaskInAPointWithCyclicBarrier.java │ └── ProducerConsumerDemo.java │ └── executor │ ├── SimpleExecutor.java │ └── FactorialCallable.java └── pom.xml /concurrent.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/concurrentDemo/master/concurrent.pptx -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | bin 3 | target 4 | .classpath 5 | .project 6 | .settings 7 | src/main/webapp/META-INF 8 | .idea 9 | *.iml 10 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/atomic/AtomicInteger.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.atomic; 2 | 3 | public class AtomicInteger { 4 | 5 | public static void main(String[] args) { 6 | final IntClass intClass = new IntClass(); 7 | Thread[] threads = new Thread[1000]; 8 | for (int i = 0; i < threads.length; i++) { 9 | threads[i] = new Thread(new Runnable() { 10 | public void run() { 11 | intClass.a(); 12 | } 13 | }, i+""); 14 | threads[i].start(); 15 | } 16 | } 17 | } 18 | 19 | class IntClass{ 20 | int i = 0; 21 | 22 | public void a(){ 23 | ++i; 24 | System.out.println(i); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/basic/InterruptDemo.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.basic; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | 5 | public class InterruptDemo { 6 | public static void main(String[] args) { 7 | Thread task = new Thread(new PrimeGenerator()); 8 | task.start(); 9 | try { 10 | TimeUnit.MILLISECONDS.sleep(500); 11 | } catch (InterruptedException e) { 12 | e.printStackTrace(); 13 | } 14 | task.interrupt(); 15 | 16 | } 17 | } 18 | 19 | class PrimeGenerator implements Runnable{ 20 | 21 | 22 | public void run() { 23 | long number = 1L; 24 | while(true){ 25 | if(isPrime(number)){ 26 | System.out.printf("Number %d is Prime \n ",number); 27 | } 28 | if(Thread.currentThread().isInterrupted()){ 29 | System.out.println("The prime generator has been interrupted"); 30 | return; 31 | } 32 | number++; 33 | } 34 | } 35 | 36 | private boolean isPrime(long number){ 37 | if(number <= 2){ 38 | return true; 39 | } 40 | for(long i = 2;i> results = Lists.newArrayList(); 20 | for (int i = 0; i < 10; i++) { 21 | results.add(executor.submit(new TaskWithResult(i))); //submit produce the future 22 | } 23 | for (Future e : results) { 24 | try { 25 | System.out.println(e.get()); 26 | } catch (InterruptedException e1) { 27 | e1.printStackTrace(); 28 | } catch (ExecutionException e1) { 29 | e1.printStackTrace(); 30 | }finally{ 31 | executor.shutdown(); 32 | } 33 | } 34 | } 35 | } 36 | 37 | class TaskWithResult implements Callable { 38 | private int id; 39 | 40 | public TaskWithResult(int id) { 41 | this.id = id; 42 | } 43 | 44 | 45 | public String call() { 46 | return "result of Task with result" + id; 47 | } 48 | 49 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.shawn 7 | concurrentDemo 8 | 1.0-SNAPSHOT 9 | 10 | 13.0 11 | com.google.guava 12 | 13 | 14 | 15 | ${guava.groupid} 16 | guava 17 | ${guava.version} 18 | 19 | 20 | org.apache.commons 21 | commons-lang3 22 | 3.1 23 | 24 | 25 | junit 26 | junit 27 | 4.11 28 | 29 | 30 | 31 | 32 | ${project.artifactId} 33 | 34 | 35 | org.apache.maven.plugins 36 | maven-compiler-plugin 37 | 2.0.2 38 | 39 | 1.6 40 | 1.6 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/util/PrintQueueWithSemaphore.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.util; 2 | 3 | import java.util.concurrent.Semaphore; 4 | 5 | public class PrintQueueWithSemaphore { 6 | public static void main(String[] args){ 7 | PrintQueueV printQueueV=new PrintQueueV(); 8 | Thread thread[]=new Thread[10]; 9 | for (int i=0; i<10; i++){ 10 | thread[i]=new Thread(new JobV(printQueueV),"Thread"+i); 11 | } 12 | for (int i=0; i<10; i++){ 13 | thread[i].start(); 14 | } 15 | } 16 | 17 | } 18 | 19 | 20 | class JobV implements Runnable{ 21 | private PrintQueueV printQueueV; 22 | 23 | public JobV(PrintQueueV printQueueV){ 24 | this.printQueueV = printQueueV; 25 | } 26 | 27 | public void run() { 28 | System.out.printf("%s: Going to print a job\n",Thread.currentThread().getName()); 29 | printQueueV.printJob(new Object()); 30 | System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName()); 31 | } 32 | } 33 | 34 | class PrintQueueV{ 35 | private final Semaphore semaphore; 36 | 37 | public PrintQueueV(){ 38 | this.semaphore = new Semaphore(1); 39 | } 40 | 41 | public void printJob(Object document){ 42 | try { 43 | semaphore.acquire(); 44 | long duration=(long)(Math.random()*10); 45 | System.out.printf("%s: PrintQueue: Printing a Job during %d seconds\n",Thread.currentThread().getName(),duration); 46 | Thread.sleep(duration); 47 | 48 | }catch (InterruptedException e){ 49 | e.printStackTrace(); 50 | }finally { 51 | semaphore.release(); 52 | } 53 | } 54 | } 55 | 56 | 57 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/basic/ThreadInitExample.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.basic; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | 6 | public class ThreadInitExample { 7 | public static void main(String[] args) { 8 | //LiftOffRun(); 9 | executorRun(); 10 | } 11 | 12 | static void LiftOffRun(){ 13 | Thread[] threads = new Thread[10]; 14 | for (int i = 0; i < threads.length; i++) { 15 | Thread thread = new Thread(new LiftOff()); 16 | thread.start(); 17 | } 18 | /* 19 | LiftOff off = new LiftOff(10); 20 | Thread thread = new Thread(off); 21 | off.run();*/ 22 | //thread.start(); 23 | } 24 | static void executorRun(){ 25 | //ExecutorService executorService = Executors.newCachedThreadPool();//create as many threads as needed 26 | //ExecutorService executorService = Executors.newSingleThreadExecutor();//each tasks will be queued and run to completion b4 the next is begun 27 | ExecutorService executorService = Executors.newFixedThreadPool(5);//threads are reused when possible 28 | for (int i = 0; i < 5; i++) { 29 | executorService.execute(new LiftOff()); 30 | } 31 | executorService.shutdown(); 32 | } 33 | } 34 | 35 | class LiftOff implements Runnable{ 36 | int countDown = 10; 37 | private static int taskCount =0; 38 | private final int id = taskCount++; 39 | 40 | public LiftOff() { 41 | } 42 | public LiftOff(int countDown){ 43 | this.countDown = countDown; 44 | } 45 | 46 | public String status(){ 47 | return "#" + id + "("+(countDown >0 ?countDown:"liftOff!")+")"; 48 | } 49 | 50 | public void run() { 51 | while (countDown-- > 0) { 52 | System.out.println(status()); 53 | Thread.yield();//moves CPU from one thread to another 54 | } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/executor/SimpleExecutor.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.executor; 2 | 3 | import java.util.Date; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.ThreadPoolExecutor; 6 | import java.util.concurrent.TimeUnit; 7 | 8 | public class SimpleExecutor { 9 | public static void main(String[] args) { 10 | ExecutorServer server = new ExecutorServer(); 11 | for (int i = 0; i < 100; i++) { 12 | Task task = new Task("Task " + i); 13 | server.executeTask(task); 14 | } 15 | server.endServer(); 16 | } 17 | } 18 | 19 | class Task implements Runnable{ 20 | private Date initDate; 21 | private String name; 22 | 23 | public Task(String name){ 24 | initDate = new Date(); 25 | this.name = name; 26 | } 27 | 28 | public void run() { 29 | System.out.printf("%s: Task %s: Created on: %s \n",Thread.currentThread().getName(),name,initDate); 30 | System.out.printf("%s: Task %s: Started on: %s \n",Thread.currentThread().getName(),name,new Date()); 31 | try { 32 | Long duration = (long)(Math.random()*10); 33 | System.out.printf("%s: Task %s: Doing a task during %d seconds \n",Thread.currentThread().getName(),name,duration); 34 | TimeUnit.SECONDS.sleep(duration); 35 | } catch (Exception e) { 36 | e.printStackTrace(); 37 | } 38 | System.out.printf("%s: Task %s:Finished on: %s \n",Thread.currentThread().getName(),name,new Date()); 39 | } 40 | } 41 | 42 | class ExecutorServer { 43 | private ThreadPoolExecutor executor; 44 | public ExecutorServer() { 45 | //executor = (ThreadPoolExecutor)Executors.newCachedThreadPool(); 46 | executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(50); 47 | } 48 | 49 | public void executeTask(Task task){ 50 | System.out.printf("Server: A new task has arrived \n"); 51 | executor.execute(task); 52 | System.out.printf("Server: largest number pool size: %d \n",executor.getLargestPoolSize()); 53 | System.out.printf("Server: pool Size: %d \n",executor.getPoolSize()); 54 | System.out.printf("Server: Active count; %d\n",executor.getActiveCount()); 55 | System.out.printf("Server: Completed Tasks: %d\n",executor.getCompletedTaskCount()); 56 | } 57 | 58 | public void endServer(){ 59 | executor.shutdown(); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/basic/SyncBankAccount.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.basic; 2 | 3 | public class SyncBankAccount { 4 | public static void main(String[] args) { 5 | Account account = new Account(); 6 | account.setBalance(1000); 7 | Company company = new Company(account); 8 | Thread companyThread = new Thread(company); 9 | 10 | Bank bank = new Bank(account); 11 | Thread bankThread = new Thread(bank); 12 | System.out.printf("Account : Initial Balance: %f\n", account.getBalance()); 13 | companyThread.start(); 14 | bankThread.start(); 15 | 16 | try { 17 | companyThread.join(); 18 | bankThread.join(); 19 | System.out.printf("Account : Final Balance: %f\n", account.getBalance()); 20 | } catch (InterruptedException e) { 21 | e.printStackTrace(); 22 | } 23 | } 24 | 25 | } 26 | 27 | class Company implements Runnable { 28 | private Account account; 29 | 30 | public Company(Account account) { 31 | this.account = account; 32 | } 33 | 34 | public void run() { 35 | for (int i = 0; i < 100; i++) { 36 | account.addAmount(1000); 37 | } 38 | } 39 | 40 | } 41 | 42 | class Bank implements Runnable { 43 | 44 | private Account account; 45 | 46 | public Bank(Account account) { 47 | this.account = account; 48 | } 49 | 50 | public void run() { 51 | for (int i = 0; i < 100; i++) { 52 | account.subtractAmount(1000); 53 | } 54 | } 55 | 56 | } 57 | 58 | class Account { 59 | private double balance; 60 | 61 | public double getBalance() { 62 | return balance; 63 | } 64 | 65 | public void setBalance(double balance) { 66 | this.balance = balance; 67 | } 68 | 69 | public synchronized void addAmount(double amount) { 70 | double tmp = this.balance; 71 | /*try { 72 | Thread.sleep(10); 73 | } catch (Exception e) { 74 | e.printStackTrace(); 75 | }*/ 76 | tmp += amount; 77 | balance = tmp; 78 | System.out.println("balance " + balance); 79 | } 80 | 81 | public synchronized void subtractAmount(double amount) { 82 | double tmp = balance; 83 | /*try { 84 | Thread.sleep(10); 85 | } catch (Exception e) { 86 | e.printStackTrace(); 87 | }*/ 88 | 89 | tmp -= amount; 90 | balance = tmp; 91 | System.out.println("balance " + balance); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/util/CountDownLatchDemo.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.util; 2 | 3 | import java.util.concurrent.CountDownLatch; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | public class CountDownLatchDemo { 7 | 8 | public static void main(String[] args) throws InterruptedException { 9 | CountDownLatch startLatch = new CountDownLatch(1); 10 | VideoConference conference = new VideoConference(10,startLatch); 11 | Thread threadConference = new Thread(conference); 12 | threadConference.start(); 13 | 14 | for (int i = 0; i < 10; i++) { 15 | Participant participant = new Participant(conference, "participant " + i); 16 | Thread thread = new Thread(participant); 17 | thread.start(); 18 | } 19 | startLatch.await(); 20 | System.out.println("Video conference started "); 21 | } 22 | } 23 | 24 | 25 | 26 | class VideoConference implements Runnable{ 27 | 28 | private final CountDownLatch controller; 29 | private CountDownLatch startLatch; 30 | public VideoConference(int number,CountDownLatch startLatch) { 31 | controller = new CountDownLatch(number); 32 | this.startLatch = startLatch; 33 | } 34 | 35 | public void arrive(String name){ 36 | System.out.printf("%s has arrived. ",name); 37 | controller.countDown(); 38 | System.out.printf("Video conference: waiting for %d participants. \n",controller.getCount()); 39 | } 40 | public void run() { 41 | System.out.printf("Video conference: Initialization: %d participants.\n",controller.getCount()); 42 | try { 43 | controller.await(); 44 | System.out.printf("Video conference: All the participants have come \n "); 45 | System.out.printf("Video conference: It's ready...\n"); 46 | startLatch.countDown(); 47 | } catch (Exception e) { 48 | e.printStackTrace(); 49 | } 50 | } 51 | 52 | } 53 | 54 | class Participant implements Runnable{ 55 | private VideoConference videoConference; 56 | private String name; 57 | 58 | public Participant(VideoConference videoConference,String name) { 59 | this.videoConference = videoConference; 60 | this.name = name; 61 | } 62 | 63 | public void run() { 64 | long duration = (long)(Math.random()*10); 65 | try { 66 | TimeUnit.SECONDS.sleep(duration); 67 | } catch (Exception e) { 68 | e.printStackTrace(); 69 | } 70 | videoConference.arrive(name); 71 | } 72 | 73 | 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/util/PrintQueueWithReentrantLock.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.util; 2 | 3 | import java.util.concurrent.locks.Lock; 4 | import java.util.concurrent.locks.ReentrantLock; 5 | 6 | 7 | public class PrintQueueWithReentrantLock { 8 | public static void main(String[] args) { 9 | PrintQueue printQueue = new PrintQueue(); 10 | Thread[] threads = new Thread[10]; 11 | for (int i = 0; i < threads.length; i++) { 12 | threads[i] = new Thread(new Job(printQueue), "Thread " + i); 13 | } 14 | 15 | for (int i = 0; i < threads.length; i++) { 16 | threads[i].start(); 17 | } 18 | } 19 | } 20 | 21 | class Job implements Runnable { 22 | private PrintQueue printQueue; 23 | 24 | public Job(PrintQueue printQueue) { 25 | this.printQueue = printQueue; 26 | } 27 | 28 | public void run() { 29 | System.out.printf("%s: Going to print a document\n", Thread.currentThread().getName()); 30 | printQueue.printJob(new Object()); 31 | // printQueue.printJobWithTimeDuration(new Object()); 32 | System.out.printf("%s: The document has been printed\n", Thread.currentThread().getName()); 33 | } 34 | 35 | } 36 | 37 | class PrintQueue { 38 | // private final Lock queueLock = new ReentrantLock(); 39 | private final Lock queueLock = new ReentrantLock(true); 40 | 41 | public void printJob(Object document) { 42 | if (queueLock.tryLock()) { 43 | /** 44 | * alternatively:queueLock.lock(); 45 | * 46 | */ 47 | 48 | try { 49 | Long duration = (long) (Math.random() * 100); 50 | System.out.println(Thread.currentThread().getName() + ":PrintQueue: Printing a Job during " + (duration / 1000) + " seconds"); 51 | Thread.sleep(duration); 52 | } catch (InterruptedException e) { 53 | e.printStackTrace(); 54 | } 55 | } 56 | /* 57 | * alternative: finally { queueLock.unlock(); } } 58 | */ 59 | } 60 | 61 | public void printJobWithTimeDuration(Object document) { 62 | for (int i = 0; i < 2; i++) { 63 | queueLock.lock(); 64 | try { 65 | Long duration = (long) (Math.random() * 5000); 66 | System.out.println(Thread.currentThread().getName() + ":PrintQueue: Printing a Job during " + (duration / 1000) + " seconds"); 67 | Thread.sleep(duration); 68 | } catch (InterruptedException e) { 69 | e.printStackTrace(); 70 | } finally { 71 | queueLock.unlock(); 72 | } 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/executor/FactorialCallable.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.executor; 2 | 3 | import java.util.List; 4 | import java.util.Random; 5 | import java.util.concurrent.Callable; 6 | import java.util.concurrent.Executors; 7 | import java.util.concurrent.Future; 8 | import java.util.concurrent.ThreadPoolExecutor; 9 | import java.util.concurrent.TimeUnit; 10 | 11 | import com.google.common.collect.Lists; 12 | 13 | public class FactorialCallable { 14 | public static void main(String[] args) { 15 | ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newFixedThreadPool(2); 16 | List> resultList = Lists.newArrayList(); 17 | 18 | Random random = new Random(); 19 | for (int i = 0; i < 10; i++) { 20 | Integer number = random.nextInt(10); 21 | FactorialCalculator calculator = new FactorialCalculator(number); 22 | Future result = executor.submit(calculator); 23 | resultList.add(result); 24 | } 25 | do { 26 | System.out.printf("Main: Number of completed tasks: %d \n",executor.getCompletedTaskCount()); 27 | for (int i = 0; i < resultList.size(); i++) { 28 | Future result = resultList.get(i); 29 | System.out.printf("Main : Task %d: %s\n",i,result.isDone()); 30 | } 31 | try { 32 | TimeUnit.MILLISECONDS.sleep(50); 33 | } catch (Exception e) { 34 | e.printStackTrace(); 35 | } 36 | } while (executor.getCompletedTaskCount() < resultList.size()); 37 | System.out.printf("Main: Result. \n"); 38 | for (int i = 0; i < resultList.size(); i++) { 39 | Future result = resultList.get(i); 40 | Integer number = null; 41 | try { 42 | number = result.get(); 43 | } catch (Exception e) { 44 | e.printStackTrace(); 45 | } 46 | System.out.printf("Main: Task %d: %d \n",i,number); 47 | } 48 | executor.shutdown(); 49 | } 50 | } 51 | 52 | class FactorialCalculator implements Callable{ 53 | 54 | private Integer number; 55 | 56 | public FactorialCalculator(Integer number){ 57 | this.number = number; 58 | } 59 | public Integer call() throws Exception { 60 | int result = 1; 61 | if((number ==0) || (number==1)){ 62 | result = 1; 63 | }else { 64 | for (int i = 2; i < number; i++) { 65 | result*=i; 66 | TimeUnit.MILLISECONDS.sleep(20); 67 | } 68 | } 69 | System.out.printf("%s: %d \n",Thread.currentThread().getName(),result); 70 | return result; 71 | } 72 | 73 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/util/PriceInfoWithReadWriteLockDemo.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.util; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.TimeUnit; 5 | import java.util.concurrent.locks.ReentrantReadWriteLock; 6 | import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock; 7 | import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; 8 | import com.google.common.collect.Lists; 9 | 10 | public class PriceInfoWithReadWriteLockDemo { 11 | public static void main(String[] args) { 12 | PricesInfo pricesInfo = new PricesInfo(); 13 | List list = Lists.newArrayList(); 14 | 15 | for (int i=0; i<5; i++){ 16 | list.add(new Thread(new Reader(pricesInfo),"reader"+i)); 17 | } 18 | list.add(new Thread(new Writer(pricesInfo),"writer ")); 19 | 20 | for (Thread thread:list) { 21 | thread.start(); 22 | } 23 | 24 | } 25 | } 26 | 27 | 28 | class Reader implements Runnable{ 29 | private PricesInfo pricesInfo; 30 | public Reader(PricesInfo pricesInfo) { 31 | this.pricesInfo = pricesInfo; 32 | } 33 | public void run() { 34 | for (int i=0; i<10; i++){ 35 | System.out.printf("%s: Price 1: %f\n", Thread.currentThread().getName(),pricesInfo.getPrice1()); 36 | System.out.printf("%s: Price 2: %f\n", Thread.currentThread().getName(),pricesInfo.getPrice2()); 37 | } 38 | } 39 | 40 | } 41 | class Writer implements Runnable{ 42 | private PricesInfo pricesInfo; 43 | public Writer(PricesInfo pricesInfo) { 44 | this.pricesInfo = pricesInfo; 45 | } 46 | 47 | public void run() { 48 | double price1 = Math.random()*10; 49 | double price2 = Math.random()*8; 50 | try { 51 | TimeUnit.MILLISECONDS.sleep(20); 52 | } catch (InterruptedException e) { 53 | e.printStackTrace(); 54 | } 55 | pricesInfo.setPrices(price1, price2); 56 | } 57 | } 58 | 59 | class PricesInfo{ 60 | private double price1; 61 | private double price2; 62 | 63 | final private ReadLock readLock; 64 | final private WriteLock writeLock; 65 | public PricesInfo(){ 66 | price1=1.0; 67 | price2=2.0; 68 | ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); 69 | readLock = readWriteLock.readLock(); 70 | writeLock = readWriteLock.writeLock(); 71 | } 72 | 73 | public double getPrice1() { 74 | readLock.lock(); 75 | double value = price1; 76 | readLock.unlock(); 77 | return value; 78 | } 79 | 80 | public double getPrice2() { 81 | readLock.lock(); 82 | double value = price2; 83 | readLock.unlock(); 84 | return value; 85 | } 86 | 87 | public void setPrices(double price1,double price2) { 88 | writeLock.lock(); 89 | System.out.printf("%s: Attempt to modify the prices with price1 %f, price2 %f.\n",Thread.currentThread().getName(),price1,price2); 90 | this.price1 = price1; 91 | this.price2 = price2; 92 | System.out.printf("%s: Prices have been modified.\n",Thread.currentThread().getName()); 93 | writeLock.unlock(); 94 | } 95 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/util/ExchangeDataInConTask.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.util; 2 | 3 | import java.util.List; 4 | import java.util.concurrent.Exchanger; 5 | 6 | import com.google.common.collect.Lists; 7 | 8 | public class ExchangeDataInConTask { 9 | public static void main(String[] args) { 10 | List buffer1 =Lists.newArrayList(); 11 | List buffer2 = Lists.newArrayList(); 12 | 13 | Exchanger> exchanger = new Exchanger>(); 14 | 15 | ExchangeProducer producer = new ExchangeProducer(buffer1,exchanger); 16 | ExchangeConsumer consumer = new ExchangeConsumer(buffer2, exchanger); 17 | 18 | Thread threadProducer = new Thread(producer); 19 | Thread threadConsumer = new Thread(consumer); 20 | 21 | threadConsumer.start(); 22 | threadProducer.start(); 23 | } 24 | } 25 | 26 | class ExchangeProducer implements Runnable{ 27 | private List buffer; 28 | 29 | private final Exchanger> exchanger; 30 | 31 | public ExchangeProducer(List buffer, Exchanger> exhcanger){ 32 | this.buffer = buffer; 33 | this.exchanger = exhcanger; 34 | } 35 | 36 | public void run() { 37 | int cycle = 1; 38 | for (int i = 0; i < 10; i++) { 39 | System.out.printf("Producer: cycle %d \n",cycle); 40 | for (int j = 0; j < 10; j++) { 41 | String message = "Event " + ((i*10) + j); 42 | System.out.printf("Producer: %s\n",message); 43 | buffer.add(message); 44 | } 45 | try { 46 | buffer = exchanger.exchange(buffer); 47 | } catch (Exception e) { 48 | e.printStackTrace(); 49 | } 50 | System.out.println("Producer: " + buffer.size()); 51 | cycle++; 52 | } 53 | } 54 | } 55 | 56 | class ExchangeConsumer implements Runnable{ 57 | private List buffer; 58 | 59 | private final Exchanger> exchanger; 60 | 61 | public ExchangeConsumer(List buffer, Exchanger> exchanger){ 62 | this.buffer = buffer; 63 | this.exchanger = exchanger; 64 | } 65 | 66 | public void run() { 67 | int cycle = 1; 68 | for (int i = 0; i < 10; i++) { 69 | System.out.printf("Consumer: Cycle %d \n",cycle); 70 | try { 71 | buffer = exchanger.exchange(buffer); 72 | } catch (Exception e) { 73 | e.printStackTrace(); 74 | } 75 | System.out.println("Consumer: " + buffer.size()); 76 | for (int j = 0; j < 10; j++) { 77 | String message = buffer.get(0); 78 | System.out.println("Consumer: " + message); 79 | buffer.remove(0); 80 | } 81 | cycle++; 82 | } 83 | } 84 | } 85 | 86 | 87 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/util/PrintQueueWithMultiRecSemaphore.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.util; 2 | 3 | import java.util.concurrent.Semaphore; 4 | import java.util.concurrent.TimeUnit; 5 | import java.util.concurrent.locks.Lock; 6 | import java.util.concurrent.locks.ReentrantLock; 7 | 8 | public class PrintQueueWithMultiRecSemaphore { 9 | public static void main(String[] args){ 10 | PrintQueueWithMultiRec printQueueWithMultiRec=new PrintQueueWithMultiRec(); 11 | Thread thread[]=new Thread[10]; 12 | for (int i=0; i<10; i++){ 13 | thread[i]=new Thread(new JobWithMultiRec(printQueueWithMultiRec),"Thread"+i); 14 | } 15 | for (int i=0; i<10; i++){ 16 | thread[i].start(); 17 | } 18 | } 19 | } 20 | 21 | 22 | class JobWithMultiRec implements Runnable{ 23 | private PrintQueueWithMultiRec printQueueWithMultiRec; 24 | 25 | public JobWithMultiRec(PrintQueueWithMultiRec printQueueWithMultiRec){ 26 | this.printQueueWithMultiRec = printQueueWithMultiRec; 27 | } 28 | 29 | public void run() { 30 | System.out.printf("%s: Going to print a job\n",Thread.currentThread().getName()); 31 | printQueueWithMultiRec.printJob(new Object()); 32 | System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName()); 33 | } 34 | } 35 | 36 | class PrintQueueWithMultiRec{ 37 | private boolean freePrinters[]; 38 | private Lock lockPrinters; 39 | private Semaphore semaphore; 40 | public PrintQueueWithMultiRec() { 41 | semaphore = new Semaphore(3); 42 | freePrinters = new boolean[3]; 43 | for (int i = 0; i < freePrinters.length; i++) { 44 | freePrinters[i] = true; 45 | } 46 | lockPrinters = new ReentrantLock(); 47 | } 48 | 49 | public void printJob(Object document){ 50 | try { 51 | semaphore.acquire(); 52 | int assignedPrinter = getPrinter(); 53 | long duration = (long) (Math.random()*10); 54 | System.out.printf("%s: printQueue: Printing a job in Printer %d during %d seconds \n", Thread.currentThread().getName(),assignedPrinter,duration); 55 | TimeUnit.SECONDS.sleep(duration); 56 | freePrinters[assignedPrinter] = true; 57 | } catch (Exception e) { 58 | e.printStackTrace(); 59 | }finally{ 60 | semaphore.release(); 61 | } 62 | } 63 | 64 | private int getPrinter(){ 65 | int ret = -1; 66 | try { 67 | lockPrinters.lock(); 68 | for (int i = 0; i < freePrinters.length; i++) { 69 | if (freePrinters[i]) { 70 | ret =i; 71 | freePrinters[i] = false; 72 | break; 73 | } 74 | } 75 | } catch (Exception e) { 76 | e.printStackTrace(); 77 | }finally{ 78 | lockPrinters.unlock(); 79 | } 80 | return ret; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/util/ExecutorServer.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.util; 2 | 3 | 4 | import java.util.Date; 5 | import java.util.Iterator; 6 | import java.util.List; 7 | import java.util.Set; 8 | import java.util.concurrent.ExecutionException; 9 | import java.util.concurrent.Executors; 10 | import java.util.concurrent.Future; 11 | import java.util.concurrent.ThreadPoolExecutor; 12 | import java.util.concurrent.TimeUnit; 13 | import java.util.concurrent.locks.ReentrantLock; 14 | 15 | import com.google.common.collect.Lists; 16 | import com.google.common.collect.Sets; 17 | 18 | 19 | 20 | public class ExecutorServer { 21 | static ReentrantLock lock = new ReentrantLock(); 22 | 23 | public static void main(String[] args) throws InterruptedException, ExecutionException { 24 | Server server = new Server(); 25 | Set sets = Sets.newCopyOnWriteArraySet(); 26 | List futures = Lists.newArrayList(); 27 | for (int i = 0; i < 10; i++) { 28 | Task task = new Task("Task " + i, sets); 29 | futures.add(server.executeTask(task)); 30 | //server.executeTask(task); 31 | } 32 | for (Future future:futures) { 33 | future.get(); 34 | } 35 | server.endServer(); 36 | Iterator iterator = sets.iterator(); 37 | while(iterator.hasNext()){ 38 | System.out.println("set ..." + iterator.next()); 39 | } 40 | 41 | 42 | 43 | } 44 | } 45 | 46 | 47 | 48 | class Server { 49 | private ThreadPoolExecutor executor; 50 | 51 | Server(){ 52 | executor = (ThreadPoolExecutor)Executors.newCachedThreadPool(); 53 | } 54 | 55 | public ThreadPoolExecutor getExecutorInstance(){ 56 | return executor; 57 | } 58 | 59 | public Future executeTask(Task task){ 60 | System.out.println("Server: new task has arrived \n"); 61 | Future future = (Future) executor.submit(task); 62 | System.out.printf("Server:%s Pool Size \n",executor.getPoolSize()); 63 | System.out.printf("Server:%s Active thread \n",executor.getActiveCount()); 64 | System.out.printf("Server:%s Completed Tasks \n",executor.getCompletedTaskCount()); 65 | return future; 66 | } 67 | 68 | 69 | public void endServer(){ 70 | executor.shutdown(); 71 | } 72 | 73 | } 74 | class Task implements Runnable{ 75 | 76 | private Date iniDate; 77 | private String name; 78 | private Set set; 79 | public Task(String name,Set sets) { 80 | iniDate = new Date(); 81 | this.name = name; 82 | this.set = sets; 83 | } 84 | public void runFun(){ 85 | System.out.printf("%s Task %s \n",Thread.currentThread().getName(),iniDate); 86 | } 87 | public void run() { 88 | runFun(); 89 | try { 90 | long duration = (long)(Math.random()*10); 91 | TimeUnit.SECONDS.sleep(duration); 92 | } catch (Exception e) { 93 | e.printStackTrace(); 94 | } 95 | set.add(name); 96 | System.out.printf("%s : Task %s:finish on : %s \n", Thread.currentThread().getName(),name,new Date()); 97 | } 98 | 99 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/basic/ReentrantLockTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.basic; 2 | 3 | public class ReentrantLockTest { 4 | 5 | static ShareObject so; 6 | 7 | public static void main(String[] args) { 8 | //final Lock lock = new SimpleLock(); 9 | 10 | final Lock lock= new ReentrantLock(); 11 | Thread[] threads = new Thread[5]; 12 | so = new ShareObject(lock); 13 | for (int i = 0; i < threads.length; i++) { 14 | threads[i] = new Thread(new Runnable() { 15 | public void run() { 16 | try { 17 | System.out.printf("%s require the lock A \n", Thread.currentThread().getName()); 18 | lock.lock(); 19 | System.out.printf("%s got the lock A \n", Thread.currentThread().getName()); 20 | so.a(); 21 | } catch (Exception e) { 22 | e.printStackTrace(); 23 | } finally { 24 | System.out.printf("%s release the lock A \n", Thread.currentThread().getName()); 25 | lock.unlock(); 26 | } 27 | } 28 | }, i + ""); 29 | } 30 | for (int i = 0; i < threads.length; i++) { 31 | threads[i].start(); 32 | } 33 | } 34 | } 35 | 36 | class ShareObject { 37 | private Lock lock; 38 | 39 | public ShareObject(Lock lock) { 40 | this.lock = lock; 41 | } 42 | 43 | public void a() { 44 | try { 45 | System.out.printf("%s require the lock B \n", Thread.currentThread().getName()); 46 | lock.lock(); 47 | System.out.printf("%s got the lock b \n", Thread.currentThread().getName()); 48 | b(); 49 | 50 | } catch (InterruptedException e) { 51 | e.printStackTrace(); 52 | } finally { 53 | System.out.printf("%s release the lock B \n", Thread.currentThread().getName()); 54 | lock.unlock(); 55 | } 56 | 57 | } 58 | 59 | public void b() { 60 | 61 | } 62 | } 63 | 64 | class ReentrantLock implements Lock { 65 | Thread lockedBy = null; 66 | boolean isLocked = false; 67 | int count = 0; 68 | 69 | public synchronized void lock() throws InterruptedException { 70 | while (count != 0 && lockedBy != Thread.currentThread()) { 71 | wait(); 72 | } 73 | isLocked = true; 74 | lockedBy = Thread.currentThread(); 75 | count++; 76 | } 77 | 78 | public synchronized void unlock() { 79 | if (lockedBy == Thread.currentThread()) { 80 | count--; 81 | if (count == 0) { 82 | isLocked = false; 83 | notify(); 84 | } 85 | } 86 | } 87 | 88 | } 89 | 90 | class SimpleLock implements Lock { 91 | Thread currentThread = null; 92 | boolean isLock = false; 93 | 94 | public synchronized void lock() throws InterruptedException { 95 | while (isLock) { 96 | wait(); 97 | } 98 | currentThread = Thread.currentThread(); 99 | isLock = true; 100 | } 101 | 102 | public synchronized void unlock() { 103 | if (currentThread == Thread.currentThread()) { 104 | isLock = false; 105 | notifyAll(); 106 | } 107 | } 108 | 109 | } 110 | 111 | interface Lock { 112 | public void lock() throws InterruptedException; 113 | 114 | public void unlock(); 115 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/basic/BasicThreadTest.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.basic; 2 | 3 | import java.io.FileWriter; 4 | import java.io.IOException; 5 | import java.io.PrintStream; 6 | import java.io.PrintWriter; 7 | import java.lang.Thread.State; 8 | 9 | 10 | 11 | public class BasicThreadTest { 12 | 13 | public static void main(String[] args) { 14 | //RunSimpleThread(); 15 | RunWithStateMonitoring(); 16 | 17 | } 18 | 19 | public static void RunSimpleThread(){ 20 | for (int i = 0; i < 10; i++) { 21 | Thread d= new Thread(new Calculator(i)); 22 | d.start(); 23 | } 24 | } 25 | 26 | public static void RunWithStateMonitoring() { 27 | Thread threads[] = new Thread[10]; 28 | Thread.State status[] = new Thread.State[10]; 29 | for (int i = 0; i < threads.length; i++) { 30 | threads[i] = new Thread(new Calculator(i)); 31 | if((i%2) == 0){ 32 | threads[i].setPriority(Thread.MAX_PRIORITY); 33 | }else { 34 | threads[i].setPriority(Thread.MIN_PRIORITY); 35 | } 36 | threads[i].setName("T " + i); 37 | } 38 | printThreadInfo(threads,status); 39 | } 40 | 41 | private static void printThreadInfo(Thread[] threads,Thread.State[] status){ 42 | 43 | 44 | try { 45 | //make file to record the states of the threads 46 | FileWriter fileWriter = new FileWriter("metadata/log.txt"); 47 | 48 | PrintWriter pw= new PrintWriter(fileWriter); 49 | for (int i = 0; i < 10; i++) { 50 | pw.println("Main: Status of Thread" + i + ":"+threads[i].getState()); 51 | status[i] = threads[i].getState(); 52 | } 53 | for (int i = 0; i < 10; i++) { 54 | threads[i].start(); 55 | } 56 | //record thread state until all threads terminates 57 | boolean finish = false; 58 | while (!finish) { 59 | for(int i=0; i<10;i++){ 60 | if(threads[i].getState()!=status[i]){ 61 | writeThreadInfo(pw,threads[i],status[i]); 62 | status[i] = threads[i].getState(); 63 | } 64 | } 65 | finish = true; 66 | for (int i = 0; i < 10; i++) { 67 | finish = finish&&(threads[i].getState() == State.TERMINATED); 68 | } 69 | } 70 | pw.close(); 71 | } catch (IOException e) { 72 | e.printStackTrace(); 73 | } 74 | } 75 | 76 | //record the threads state shifting 77 | private static void writeThreadInfo(PrintWriter pw,Thread t , State state){ 78 | //pw.printf("Main: Id %d - %s\n",t.getId(),t.getName()); 79 | pw.printf("Main: ------- %s\n",t.getName()); 80 | pw.printf("Main:Priority: %d \n",t.getPriority()); 81 | pw.printf("Main: Old State: %s\n",state); 82 | pw.printf("Main:New State: %s \n",t.getState()); 83 | pw.printf("Main:**************************************************\n"); 84 | } 85 | } 86 | 87 | 88 | //class Calculator implements Runnable{ 89 | class Calculator extends Thread{ 90 | private int number; 91 | public Calculator(int number) { 92 | this.number = number; 93 | } 94 | 95 | public void run() { 96 | for (int i = 0; i < 10; i++) { 97 | System.out.printf("%s: %d*%d = %d \n",Thread.currentThread().getName(),number,i,i*number); 98 | } 99 | } 100 | 101 | } -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/basic/BackwardThread.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.basic; 2 | 3 | import java.util.concurrent.TimeUnit; 4 | import java.util.concurrent.locks.Condition; 5 | import java.util.concurrent.locks.ReentrantLock; 6 | 7 | public class BackwardThread { 8 | 9 | public static void main(String[] args) throws InterruptedException { 10 | //runBySync(); 11 | runByReentrantLock(); 12 | } 13 | 14 | static SharedObject so = new SharedObject(); 15 | static void runBySync(){ 16 | Thread[] threads = new Thread[10]; 17 | for (int i = 0; i < threads.length; i++) { 18 | threads[i] = new ThreadSync(i,so); 19 | threads[i].start(); 20 | } 21 | 22 | } 23 | static void runByReentrantLock(){ 24 | Thread[] threads = new Thread[10]; 25 | Doc doc = new Doc(); 26 | for( int i=0; i< threads.length; i++){ 27 | threads[i] = new Thread(new DocPrint(i, doc),i+""); 28 | threads[i].start(); 29 | //threads[i]. 30 | } 31 | } 32 | } 33 | 34 | class ThreadSync extends Thread{ 35 | SharedObject sharedObject; 36 | int num; 37 | public ThreadSync(int i,SharedObject sharedObject) { 38 | this.sharedObject =sharedObject; 39 | num = i; 40 | } 41 | 42 | @Override 43 | public void run() { 44 | sharedObject.printSelf(num); 45 | } 46 | } 47 | 48 | class SharedObject { 49 | 50 | private Integer numberOfThreads = 10; 51 | //private final Object mutex = new Object(); 52 | public void printSelf(int num){ 53 | /*try { 54 | TimeUnit.SECONDS.sleep(1); 55 | System.out.println("in sleep"); 56 | } catch (InterruptedException e) { 57 | e.printStackTrace(); 58 | }*/ 59 | //System.out.println(this.toString()); 60 | try { 61 | TimeUnit.MILLISECONDS.sleep(500); 62 | System.out.println("sleep:" +Thread.currentThread().getName()); 63 | } catch (InterruptedException e1) { 64 | e1.printStackTrace(); 65 | } 66 | synchronized (this) { 67 | while((num+1) != numberOfThreads){ 68 | try { 69 | //System.out.println("before wait: " + Thread.currentThread().getName()); 70 | wait(); 71 | //System.out.println("after wait: " + Thread.currentThread().getName()); 72 | } catch (InterruptedException e) { 73 | e.printStackTrace(); 74 | } 75 | } 76 | System.out.println( num + " "+Thread.currentThread().getName()); 77 | numberOfThreads--; 78 | notifyAll(); 79 | } 80 | } 81 | } 82 | 83 | 84 | class DocPrint implements Runnable{ 85 | private Doc doc; 86 | private int id; 87 | public DocPrint(int id,Doc doc) { 88 | this.id = id; 89 | this.doc = doc; 90 | } 91 | public void run() { 92 | doc.printSelf(id); 93 | } 94 | 95 | } 96 | class Doc { 97 | private Condition number; 98 | private ReentrantLock lock; 99 | private int numOfThread = 10; 100 | 101 | public Doc() { 102 | lock = new ReentrantLock(); 103 | number = lock.newCondition(); 104 | } 105 | 106 | public void printSelf(int id) { 107 | lock.lock(); 108 | try { 109 | while(id+1 != numOfThread) { 110 | //System.out.printf("%s is waiting...\n",Thread.currentThread().getName()); 111 | number.await(); 112 | } 113 | System.out.println( id + " "+Thread.currentThread().getName()); 114 | numOfThread--; 115 | number.signalAll(); 116 | } catch (InterruptedException e) { 117 | Thread.interrupted(); 118 | }finally{ 119 | lock.unlock(); 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/util/CountNumberByCyclicBarrier.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.util; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.concurrent.BrokenBarrierException; 6 | import java.util.concurrent.Callable; 7 | import java.util.concurrent.CyclicBarrier; 8 | import java.util.concurrent.ExecutionException; 9 | import java.util.concurrent.ExecutorService; 10 | import java.util.concurrent.Executors; 11 | import java.util.concurrent.Future; 12 | 13 | import javax.swing.ListModel; 14 | 15 | import com.google.common.collect.Lists; 16 | 17 | public class CountNumberByCyclicBarrier { 18 | 19 | private long sum; 20 | // private static CyclicBarrier barrier; 21 | private List list; 22 | private int threadCounts; 23 | 24 | public static void main(String[] args) { 25 | List list = new ArrayList(); 26 | int threadCounts = 10; 27 | // barrier=new CyclicBarrier(threadCounts+1); 28 | for (int i = 1; i <= 1000000; i++) { 29 | list.add(i); 30 | } 31 | CountNumberByCyclicBarrier countListIntegerSum=new CountNumberByCyclicBarrier(list,threadCounts); 32 | long sum=countListIntegerSum.divideAndConquerSum(); 33 | System.out.println("sum:"+sum); 34 | } 35 | 36 | public CountNumberByCyclicBarrier(List list,int threadCounts) { 37 | this.list=list; 38 | this.threadCounts=threadCounts; 39 | } 40 | 41 | public long divideAndConquerSum(){ 42 | ExecutorService exec=Executors.newFixedThreadPool(threadCounts); 43 | int len=list.size()/threadCounts;//split list 44 | if(len==0){ 45 | threadCounts=list.size(); 46 | len=list.size()/threadCounts; 47 | } 48 | 49 | List> subSums = Lists.newArrayList(); 50 | for(int i=0;ilist.size()?list.size():len*(i+1))))); 55 | } 56 | } 57 | 58 | try { 59 | // barrier.await();//threads waiting in barrier 60 | for (Future e:subSums) { 61 | sum+=e.get(); 62 | } 63 | } catch (InterruptedException e) { 64 | System.out.println(Thread.currentThread().getName()+" Interrupted"); 65 | }/* catch (BrokenBarrierException e) { 66 | System.out.println(Thread.currentThread().getName()+" BrokenBarrier"); 67 | }*/ catch (ExecutionException e1) { 68 | System.out.println(Thread.currentThread().getName() +"executuon exception"); 69 | } 70 | exec.shutdown(); 71 | return sum; 72 | } 73 | 74 | 75 | class SubIntegerSumTask implements Callable{ 76 | private List subList; 77 | 78 | public SubIntegerSumTask(List subList) { 79 | this.subList=subList; 80 | } 81 | 82 | public Long call() throws Exception { 83 | long subSum=0L; 84 | if(!"pool-1-thread-10".equals(Thread.currentThread().getName())){ 85 | for (Integer i : subList) { 86 | subSum += i; 87 | } 88 | System.out.println("allocating to:"+Thread.currentThread().getName()+" total \tSubSum "+subSum); 89 | }else{ 90 | // Thread.currentThread().interrupt(); 91 | throw new Exception(); 92 | } 93 | /* try { 94 | barrier.await(); 95 | } catch (InterruptedException e) { 96 | System.out.println(Thread.currentThread().getName()+":Interrupted"); 97 | } catch (BrokenBarrierException e) { 98 | System.out.println(Thread.currentThread().getName()+":BrokenBarrier"); 99 | }*/ 100 | 101 | return subSum; 102 | } 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/com/shawn/concurrent/demo/util/SyncTaskInAPointWithCyclicBarrier.java: -------------------------------------------------------------------------------- 1 | package com.shawn.concurrent.demo.util; 2 | 3 | import java.util.Random; 4 | import java.util.concurrent.CyclicBarrier; 5 | 6 | public class SyncTaskInAPointWithCyclicBarrier { 7 | public static void main(String[] args) { 8 | final int ROWS = 10000; 9 | final int NUMBERS = 1000; 10 | final int SEARCH = 5; 11 | final int PARTICIPANT =5; 12 | final int LINES_PARTICIPANT=2000; 13 | 14 | MatrixMock mock = new MatrixMock(ROWS, NUMBERS,SEARCH); 15 | Results results = new Results(ROWS); 16 | 17 | Grouper grouper = new Grouper(results); 18 | CyclicBarrier barrier = new CyclicBarrier(PARTICIPANT,grouper); 19 | Searcher searchers[] = new Searcher[PARTICIPANT]; 20 | 21 | for (int i = 0; i < searchers.length; i++) { 22 | searchers[i] = new Searcher(i*LINES_PARTICIPANT,(i*LINES_PARTICIPANT)+LINES_PARTICIPANT, 23 | mock, results, 9, barrier); 24 | Thread thread = new Thread(searchers[i]); 25 | thread.start(); 26 | } 27 | System.out.printf("Main thread has finished.\n"); 28 | } 29 | } 30 | 31 | 32 | class Grouper implements Runnable{ 33 | private Results results; 34 | public Grouper(Results results) { 35 | this.results = results; 36 | } 37 | public void run() { 38 | int finalResult = 0; 39 | System.out.printf("Grouper: Processing results ...\n"); 40 | int data[] = results.getDta(); 41 | for(int number:data){ 42 | finalResult += number; 43 | } 44 | System.out.printf("Grouper: Total result: %d \n",finalResult); 45 | } 46 | 47 | } 48 | 49 | class Searcher implements Runnable{ 50 | private int firstRow; 51 | private int lasRow; 52 | private MatrixMock mock; 53 | private Results results; 54 | private int number; 55 | private final CyclicBarrier barrier; 56 | 57 | 58 | public Searcher(int firstRow, int lasRow, MatrixMock mock, Results results, int number, CyclicBarrier barrier) { 59 | this.firstRow = firstRow; 60 | this.lasRow = lasRow; 61 | this.mock = mock; 62 | this.results = results; 63 | this.number = number; 64 | this.barrier = barrier; 65 | } 66 | 67 | 68 | public void run() { 69 | int counter; 70 | System.out.printf("%s: Processing lines from %d to %d .\n",Thread.currentThread().getName(),firstRow,lasRow); 71 | for (int i = firstRow; i =0) && (row { 41 | private Storage storage; 42 | 43 | public Consumer(Storage storage) { 44 | this.storage = storage; 45 | } 46 | 47 | 48 | public String call() throws Exception { 49 | for (int i = 0; i < 10; i++) { 50 | try { 51 | TimeUnit.NANOSECONDS.sleep(100); 52 | } catch (InterruptedException e) { 53 | e.printStackTrace(); 54 | } 55 | storage.get(); 56 | } 57 | return null; 58 | } 59 | 60 | } 61 | 62 | class Producer implements Callable { 63 | private Storage storage; 64 | 65 | public Producer(Storage storage) { 66 | this.storage = storage; 67 | } 68 | 69 | public String call() throws Exception { 70 | for (int i = 0; i < 10; i++) { 71 | storage.set(); 72 | } 73 | return null; 74 | } 75 | } 76 | 77 | //for read write lock example 78 | class Viewer implements Callable { 79 | private Storage storage; 80 | 81 | public Viewer(Storage storage) { 82 | this.storage = storage; 83 | } 84 | 85 | public String call() throws Exception{ 86 | for (int i = 0; i < 10; i++) { 87 | try { 88 | TimeUnit.MILLISECONDS.sleep(50); 89 | } catch (InterruptedException e) { 90 | e.printStackTrace(); 91 | } 92 | storage.read(); 93 | } 94 | return null; 95 | } 96 | } 97 | 98 | class StorageWithSync extends Storage { 99 | int maxSize; 100 | LinkedList storage; 101 | 102 | public StorageWithSync(int maxSize) { 103 | this.maxSize = maxSize; 104 | storage = new LinkedList(); 105 | } 106 | 107 | public synchronized void set() { 108 | while (storage.size() == maxSize) { 109 | try { 110 | wait(); 111 | } catch (InterruptedException e) { 112 | e.printStackTrace(); 113 | } 114 | } 115 | 116 | storage.offer(new Date()); 117 | System.out.printf("Set: %d \n", storage.size()); 118 | notifyAll(); 119 | } 120 | 121 | public synchronized void get() { 122 | while (storage.size() == 0) { 123 | try { 124 | wait(); 125 | } catch (InterruptedException e) { 126 | e.printStackTrace(); 127 | } 128 | } 129 | 130 | System.out.printf("Get: %d: %s \n", storage.size(), 131 | ((LinkedList) storage).poll()); 132 | notifyAll(); 133 | } 134 | } 135 | 136 | class StorageWithCondition extends Storage { 137 | int maxSize; 138 | LinkedList storage; 139 | private final ReentrantLock reentrantLock = new ReentrantLock(true); 140 | private Condition notFull = reentrantLock.newCondition(); 141 | private Condition notEmpty = reentrantLock.newCondition(); 142 | 143 | public StorageWithCondition(int maxSize) { 144 | this.maxSize = maxSize; 145 | storage = new LinkedList(); 146 | } 147 | 148 | public void set() { 149 | reentrantLock.lock(); 150 | try { 151 | while (storage.size() == maxSize) { 152 | notFull.await(); 153 | } 154 | storage.offer(new Date()); 155 | System.out.printf("Set: %d \n", storage.size()); 156 | notEmpty.signalAll(); 157 | } catch (InterruptedException e) { 158 | System.out.printf("%s Interrupted",Thread.currentThread().getName()); 159 | }catch(IllegalMonitorStateException e){ 160 | System.out.printf("%s is locked by illegal monitor",Thread.currentThread().getName()); 161 | } finally { 162 | reentrantLock.unlock(); 163 | } 164 | } 165 | 166 | public void get() { 167 | reentrantLock.lock(); 168 | try { 169 | while (storage.size() == 0) { 170 | notEmpty.await(); 171 | } 172 | System.out.printf("Get: %d: %s \n", storage.size(), storage.poll()); 173 | notFull.signalAll(); 174 | } catch (InterruptedException e) { 175 | System.out.printf("%s Interrupted",Thread.currentThread().getName()); 176 | }catch(IllegalMonitorStateException e){ 177 | System.out.printf("%s is locked by illegal monitor",Thread.currentThread().getName()); 178 | } finally { 179 | reentrantLock.unlock(); 180 | } 181 | } 182 | 183 | } 184 | 185 | class StorageWithSemaphore extends Storage { 186 | int maxSize; 187 | LinkedList storage; 188 | private final Semaphore notFull; 189 | private final Semaphore notEmpty = new Semaphore(0,true); 190 | private final Semaphore access = new Semaphore(1,true); 191 | 192 | public StorageWithSemaphore(int maxSize) { 193 | this.maxSize = maxSize; 194 | storage = new LinkedList(); 195 | notFull = new Semaphore(maxSize,true); 196 | } 197 | 198 | public void set() { 199 | try { 200 | notFull.acquire(); 201 | access.acquire(); 202 | storage.offer(new Date()); 203 | System.out.printf("Set: %d \n", storage.size()); 204 | } catch (InterruptedException e) { 205 | System.out.println(e.toString()); 206 | } finally { 207 | access.release(); 208 | notEmpty.release(); 209 | } 210 | } 211 | 212 | public void get() { 213 | 214 | try { 215 | notEmpty.acquire(); 216 | access.acquire(); 217 | System.out.printf("Get: %d: %s \n", storage.size(), storage.poll()); 218 | } catch (InterruptedException e) { 219 | System.out.println(e.toString()); 220 | } finally { 221 | access.release(); 222 | notFull.release(); 223 | } 224 | } 225 | } 226 | 227 | 228 | class StorageReadWriteLock extends Storage { 229 | int maxSize; 230 | private LinkedList storage; 231 | private ReentrantReadWriteLock lock; 232 | private ReadLock readlock; 233 | private WriteLock writeLock; 234 | private Condition notFull; 235 | private Condition notEmpty; 236 | 237 | public StorageReadWriteLock(int maxSize) { 238 | this.maxSize = maxSize; 239 | storage = Lists.newLinkedList(); 240 | lock = new ReentrantReadWriteLock(); 241 | readlock = lock.readLock(); 242 | writeLock = lock.writeLock(); 243 | notFull = writeLock.newCondition(); 244 | notEmpty = writeLock.newCondition(); 245 | } 246 | 247 | public void set() { 248 | writeLock.lock(); 249 | try { 250 | while (storage.size() == maxSize) { 251 | notFull.await(); 252 | } 253 | storage.offer(new Date()); 254 | System.out.printf("Set: %d \n", storage.size()); 255 | notEmpty.signalAll(); 256 | } catch (InterruptedException e) { 257 | System.out.printf("%s Interrupted",Thread.currentThread().getName()); 258 | }catch(IllegalMonitorStateException e){ 259 | System.out.printf("%s is locked by illegal monitor",Thread.currentThread().getName()); 260 | } finally { 261 | writeLock.unlock(); 262 | } 263 | } 264 | 265 | public void get() { 266 | writeLock.lock(); 267 | try { 268 | while (storage.size() == 0) { 269 | notEmpty.await(); 270 | } 271 | System.out.printf("Get: %d: %s \n", storage.size(), storage.poll()); 272 | notFull.signalAll(); 273 | } catch (InterruptedException e) { 274 | System.out.printf("%s Interrupted",Thread.currentThread().getName()); 275 | }catch(IllegalMonitorStateException e){ 276 | System.out.printf("%s is locked by illegal monitor",Thread.currentThread().getName()); 277 | } finally { 278 | writeLock.unlock(); 279 | } 280 | } 281 | 282 | @Override 283 | public void read() { 284 | readlock.lock(); 285 | try { 286 | if (storage.size() != 0) { 287 | System.out.printf("%s read: %d : %s \n", Thread.currentThread() 288 | .getId(), storage.size(), 289 | storage.get(storage.size() - 1)); 290 | } else { 291 | Thread.currentThread().interrupt(); 292 | } 293 | } finally { 294 | 295 | readlock.unlock(); 296 | } 297 | } 298 | } 299 | 300 | abstract class Storage { 301 | 302 | public abstract void set(); 303 | 304 | public abstract void get(); 305 | 306 | public void read() throws Exception { 307 | throw new UnsupportedOperationException("not implemented"); 308 | } 309 | 310 | } --------------------------------------------------------------------------------