Skip to content

Commit c1daeea

Browse files
authored
Add files via upload
1 parent 1201b3a commit c1daeea

File tree

1 file changed

+368
-0
lines changed

1 file changed

+368
-0
lines changed

ThreadPoolExample.java

Lines changed: 368 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,368 @@
1+
/**
2+
*
3+
*/
4+
package org.ankit.threads.samples;
5+
6+
import static java.util.concurrent.TimeUnit.MILLISECONDS;
7+
8+
import java.util.ArrayList;
9+
import java.util.List;
10+
import java.util.concurrent.ExecutionException;
11+
import java.util.concurrent.Executor;
12+
import java.util.concurrent.ExecutorService;
13+
import java.util.concurrent.Executors;
14+
import java.util.concurrent.Future;
15+
import java.util.concurrent.ScheduledExecutorService;
16+
import java.util.concurrent.ScheduledFuture;
17+
import java.util.concurrent.TimeUnit;
18+
19+
/**
20+
* @author yz09
21+
*
22+
*/
23+
public class ThreadPoolExample {
24+
25+
/**
26+
* @param args
27+
*/
28+
public static void main(String[] args) {
29+
// spawnSingleThread();
30+
// spawnMultipleFixedThreads();
31+
// spawnMultipleCachedThreads();
32+
// spawnSingleScheduledThread();
33+
// checkDiffInScheduleExecutorAndThreadPool();
34+
checkDiffAtFixedRateAndWithFixedDelay();
35+
}
36+
37+
private static void spawnSingleThread() {
38+
/*
39+
* Creates an Executor that uses a single worker thread operating off an
40+
* unbounded queue. (Note however that if this single thread terminates
41+
* due to a failure during execution prior to shutdown, a new one will
42+
* take its place if needed to execute subsequent tasks.) Tasks are
43+
* guaranteed to execute sequentially, and no more than one task will be
44+
* active at any given time. Unlike the otherwise equivalent
45+
* newFixedThreadPool(1) the returned executor is guaranteed not to be
46+
* reconfigurable to use additional threads.
47+
*/
48+
Executor myExecutor = Executors.newSingleThreadExecutor();
49+
myExecutor.execute(() -> {
50+
51+
System.out.println(
52+
"My Thread Running" + Thread.currentThread().getName());
53+
for (int i = 100; i < 200; i++) {
54+
System.out.println("In My own Thread.." + i);
55+
try {
56+
Thread.sleep(9000);
57+
} catch (InterruptedException e) {
58+
System.out.println("Exception..."
59+
+ Thread.currentThread().isInterrupted());
60+
}
61+
}
62+
63+
});
64+
65+
for (int i = 0; i < 100; i++) {
66+
System.out.println("In Main Thread.." + i);
67+
if (i == 50) {
68+
ExecutorService service = (ExecutorService) myExecutor;
69+
service.shutdownNow();
70+
}
71+
}
72+
73+
}
74+
75+
private static void spawnMultipleFixedThreads() {
76+
/*
77+
* Creates a thread pool that reuses a fixed number of threads operating
78+
* off a shared unbounded queue. At any point, at most nThreads threads
79+
* will be active processing tasks. If additional tasks are submitted
80+
* when all threads are active, they will wait in the queue until a
81+
* thread is available. If any thread terminates due to a failure during
82+
* execution prior to shutdown, a new one will take its place if needed
83+
* to execute subsequent tasks. The threads in the pool will exist until
84+
* it is explicitly shutdown.
85+
*/
86+
Executor myExecutor = Executors.newFixedThreadPool(2);
87+
MyLock lock = new MyLock();
88+
myExecutor.execute(new EvenPrintThread(100, lock));
89+
myExecutor.execute(new OddPrintThread(100, lock));
90+
ExecutorService service = (ExecutorService) myExecutor;
91+
service.shutdown();
92+
93+
}
94+
95+
private static void spawnMultipleCachedThreads() {
96+
/*
97+
* Creates a thread pool that creates new threads as needed, but will
98+
* reuse previously constructed threads when they are available. These
99+
* pools will typically improve the performance of programs that execute
100+
* many short-lived asynchronous tasks. Calls to execute will reuse
101+
* previously constructed threads if available. If no existing thread is
102+
* available, a new thread will be created and added to the pool.
103+
* Threads that have not been used for sixty seconds are terminated and
104+
* removed from the cache. Thus, a pool that remains idle for long
105+
* enough will not consume any resources. Note that pools with similar
106+
* properties but different details (for example, timeout parameters)
107+
* may be created using ThreadPoolExecutor constructors.
108+
*/
109+
ExecutorService myExecutor = Executors.newCachedThreadPool();
110+
List<Future<String>> returnList = new ArrayList<>();
111+
for (int i = 0; i < 3; i++) {
112+
System.out.println("submitting task.." + i);
113+
Future<String> result = myExecutor.submit(() -> {
114+
try {
115+
System.out.println("Inter status..for task"
116+
+ Thread.currentThread().getId()
117+
+ Thread.currentThread().isInterrupted());
118+
System.out
119+
.println("Thread.." + Thread.currentThread().getId()
120+
+ "/....going to sleep");
121+
122+
MILLISECONDS.sleep(2000);
123+
} catch (InterruptedException ex) {
124+
Thread.currentThread().interrupt();
125+
System.out.println(
126+
"Inter caught" + Thread.currentThread().getId()
127+
+ "...status.." + Thread.interrupted());
128+
}
129+
return "I am callable for" + Thread.currentThread().getId();
130+
});
131+
returnList.add(result);
132+
}
133+
134+
System.out.println("going to shutdown pool..");
135+
myExecutor.shutdownNow();
136+
System.out.println("pool shutdown....");
137+
138+
try {
139+
for (int i = 3; i < 5; i++) {
140+
System.out.println("submitting task.." + i);
141+
Future<String> result = myExecutor.submit(() -> {
142+
try {
143+
System.out.println("Inter status..for task.."
144+
+ Thread.currentThread().getId()
145+
+ Thread.currentThread().isInterrupted());
146+
System.out.println(
147+
"Thread.." + Thread.currentThread().getId()
148+
+ "/....going to sleep");
149+
MILLISECONDS.sleep(2000);
150+
} catch (InterruptedException ex) {
151+
System.out.println("Inter caught"
152+
+ Thread.currentThread().getId() + "...status.."
153+
+ Thread.currentThread().isInterrupted());
154+
}
155+
return "I am callable for" + Thread.currentThread().getId();
156+
});
157+
returnList.add(result);
158+
}
159+
} catch (Exception ex) {
160+
System.out.println(ex.getMessage());
161+
}
162+
163+
System.out.println("going to get result..");
164+
returnList.forEach((item) -> {
165+
try {
166+
System.out.println("Result.." + item.get());
167+
} catch (ExecutionException e) {
168+
e.printStackTrace();
169+
170+
} catch (InterruptedException e) {
171+
e.printStackTrace();
172+
}
173+
});
174+
175+
}
176+
177+
private static void checkDiffAtFixedRateAndWithFixedDelay() {
178+
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
179+
180+
executor.scheduleAtFixedRate(() -> {
181+
System.out.println("My Thread running");
182+
for (int i = 0; i < 4; i++) {
183+
System.out.println(i);
184+
try {
185+
MILLISECONDS.sleep(2000);
186+
} catch (Exception e) {
187+
e.printStackTrace();
188+
}
189+
}
190+
} , 5, 1, TimeUnit.SECONDS);
191+
192+
/*
193+
* executor.scheduleWithFixedDelay(() -> { System.out.println(
194+
* "My Thread running"); for (int i = 0; i < 4; i++) {
195+
* System.out.println(i); try { MILLISECONDS.sleep(2000); } catch
196+
* (Exception e) { e.printStackTrace(); } } } , 5, 10,
197+
* TimeUnit.SECONDS);
198+
*/
199+
}
200+
201+
private static void checkDiffInScheduleExecutorAndThreadPool() {
202+
203+
/*
204+
* in this case once 1st thread finish then only second will execute as
205+
* we have only 1 worker thread ,so for second thread delay does not
206+
* matter.
207+
*/
208+
// ScheduledExecutorService executor =
209+
// Executors.newSingleThreadScheduledExecutor();
210+
211+
/*
212+
* In this case the second thread will execute after 15 second while
213+
* first thraed is being run, as we have 2 pool size executor
214+
*/
215+
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
216+
217+
executor.schedule(() -> {
218+
System.out.println("Started running...1");
219+
for (int i = 0; i < 1000000; i++) {
220+
System.out.println(i);
221+
try {
222+
MILLISECONDS.sleep(2000);
223+
} catch (Exception e) {
224+
e.printStackTrace();
225+
}
226+
}
227+
} , 10, TimeUnit.SECONDS);
228+
229+
executor.schedule(() -> {
230+
System.out.println("I am another thread");
231+
} , 12, TimeUnit.SECONDS);
232+
233+
executor.schedule(() -> {
234+
System.out.println("I am another thread 2");
235+
} , 15, TimeUnit.SECONDS);
236+
237+
executor.shutdown();
238+
239+
}
240+
241+
private static void spawnSingleScheduledThread() {
242+
243+
ScheduledExecutorService executor =
244+
Executors.newSingleThreadScheduledExecutor();
245+
246+
/*
247+
* ScheduledExecutorService executor =
248+
* Executors.newScheduledThreadPool(2);
249+
*/
250+
/*
251+
* executor.schedule(() -> { System.out.println("Beep.Once.."); } , 1,
252+
* TimeUnit.SECONDS);
253+
*
254+
* executor.scheduleAtFixedRate(() -> { System.out.println("Beep..."); }
255+
* , 10, 10, TimeUnit.SECONDS);
256+
*/
257+
258+
final ScheduledFuture<?> handle = executor.schedule(() -> {
259+
System.out.println(
260+
"You have not done any activity..so logging you out..");
261+
} , 120, TimeUnit.SECONDS);
262+
263+
executor.schedule(() -> {
264+
System.out.println("Activity done...so cacnelling timer");
265+
// handle.cancel(true);
266+
System.out.println("Scheduling a 2 min timer again...");
267+
executor.schedule(() -> {
268+
System.out.println(
269+
"You have not done any activity..so logging you out..");
270+
} , 120, TimeUnit.SECONDS);
271+
} , 130, TimeUnit.SECONDS);
272+
273+
try {
274+
executor.awaitTermination(250, TimeUnit.SECONDS);
275+
} catch (InterruptedException e) {
276+
System.out.println("Ineruppt while awaitTermination");
277+
}
278+
279+
System.out.println("Shutdown starts..");
280+
executor.shutdown();
281+
System.out.println("Shutdown completes..");
282+
283+
}
284+
285+
}
286+
287+
class MyLock {
288+
private boolean flag;
289+
290+
public boolean isFlag() {
291+
return flag;
292+
}
293+
294+
public void setFlag(boolean flag) {
295+
this.flag = flag;
296+
}
297+
298+
}
299+
300+
class EvenPrintThread implements Runnable {
301+
302+
private int numberLimit;
303+
private MyLock lock;
304+
305+
public EvenPrintThread(int numberLimit, MyLock lock) {
306+
this.lock = lock;
307+
this.numberLimit = numberLimit;
308+
}
309+
310+
@Override
311+
public void run() {
312+
int counter = 0;
313+
while (counter < numberLimit) {
314+
synchronized (lock) {
315+
while (lock.isFlag()) {
316+
try {
317+
lock.wait();
318+
} catch (InterruptedException ex) {
319+
320+
}
321+
}
322+
323+
if (counter % 2 == 0) {
324+
System.out.println("EvenPrintThread.." + counter);
325+
}
326+
lock.setFlag(true);
327+
counter++;
328+
lock.notifyAll();
329+
}
330+
}
331+
}
332+
333+
}
334+
335+
class OddPrintThread implements Runnable {
336+
337+
private int numberLimit;
338+
private MyLock lock;
339+
340+
public OddPrintThread(int numberLimit, MyLock lock) {
341+
this.numberLimit = numberLimit;
342+
this.lock = lock;
343+
}
344+
345+
@Override
346+
public void run() {
347+
int counter = 0;
348+
while (counter < numberLimit) {
349+
synchronized (lock) {
350+
while (!lock.isFlag()) {
351+
try {
352+
lock.wait();
353+
} catch (InterruptedException ex) {
354+
355+
}
356+
}
357+
358+
if (counter % 2 != 0) {
359+
System.out.println("OddPrintThread..." + counter);
360+
}
361+
lock.setFlag(false);
362+
counter++;
363+
lock.notifyAll();
364+
}
365+
}
366+
}
367+
368+
}

0 commit comments

Comments
 (0)