Skip to content

Instantly share code, notes, and snippets.

@wang-nima
Created December 14, 2020 08:12
Show Gist options
  • Save wang-nima/ff2ae2bdb44fc91b205b6fbc6a9d8540 to your computer and use it in GitHub Desktop.
Save wang-nima/ff2ae2bdb44fc91b205b6fbc6a9d8540 to your computer and use it in GitHub Desktop.
// Java program to illustrate
// ThreadPool
package com.company;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.TimeUnit;
// Task class to be executed (Step 1)
class Task implements Runnable
{
private List<Integer> l;
private ReentrantLock lock;
public Task(List<Integer> l, ReentrantLock lock)
{
this.l = l;
this.lock = lock;
}
// Prints task name and sleeps for 1s
// This Whole process is repeated 5 times
@Override
public void run()
{
for (int i = 0; i < 10000; i++)
{
lock.lock();
int temp = l.get(0);
lock.unlock();
temp += 1;
lock.lock();
l.set(0, temp);
lock.unlock();
}
}
}
public class Main
{
// Maximum number of threads in thread pool
static final int MAX_T = 2;
public static void main(String[] args)
{
List<Integer> l = new ArrayList<>();
ReentrantLock lock = new ReentrantLock();
l.add(0);
// creates five tasks
Runnable r1 = new Task(l, lock);
Runnable r2 = new Task(l, lock);
// creates a thread pool with MAX_T no. of
// threads as the fixed pool size(Step 2)
ExecutorService pool = Executors.newFixedThreadPool(MAX_T);
// passes the Task objects to the pool to execute (Step 3)
pool.execute(r1);
pool.execute(r2);
// pool.execute(r3);
// pool.execute(r4);
// pool.execute(r5);
// pool shutdown ( Step 4)
pool.shutdown();
try {
pool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(l.get(0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment