Skip to content

Instantly share code, notes, and snippets.

@jawardell
Last active August 27, 2017 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jawardell/ec9da0cc6b324c866b76be8fd72fc64e to your computer and use it in GitHub Desktop.
Save jawardell/ec9da0cc6b324c866b76be8fd72fc64e to your computer and use it in GitHub Desktop.
Threading Exercises
/*
*Write code to implement a
*Producer-Consumer model which
*utilizes the Guarded Block
*paradigm.
*/
import java.util.concurrent.*;
public class Driver3 {
public static DropBox dropbox = new DropBox();
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Producer(dropbox));
executor.execute(new Consumer(dropbox));
executor.shutdown();
while(!executor.isTerminated()){}
System.out.println("Complete " + Thread.currentThread().getName());
}
public static class Producer implements Runnable {
private DropBox dropbox;
public Producer(DropBox dropbox) {
this.dropbox = dropbox;
}
public void run() {
Product product = new Product();
System.out.println(dropbox.put(product));
System.out.println("Placed1 " + Thread.currentThread().getName() + " Producer");
try {
Thread.sleep(2000);
Product product1 = new Product();
System.out.println(dropbox.put(product1));
System.out.println("Placed2 " + Thread.currentThread().getName() + " Producer");
}catch(InterruptedException e){}
}
}
public static class Consumer implements Runnable {
private DropBox dropbox;
public Consumer(DropBox dropbox) {
this.dropbox = dropbox;
}
public void run() {
System.out.println(dropbox.take());
System.out.println("Taken1 " + Thread.currentThread().getName() + " Consumer");
try {
Thread.sleep(2000);
System.out.println(dropbox.take());
System.out.println("Taken2 " + Thread.currentThread().getName() + " Consumer");
}catch(InterruptedException e){}
}
}
public static class Product{}
public static class DropBox {
Product product;
boolean isFull = false;
public synchronized String put(Product product) {
while(isFull) {
try {
wait();
}catch(InterruptedException e){}
}
isFull = true;
this.product = product;
notifyAll();
return "putting..";
}
public synchronized String take() {
while(!isFull) {
try {
wait();
}catch(InterruptedException e){}
}
isFull = false;
product = null;
notifyAll();
return "taking..";
}
}
}
public class TenThreads {
public static int count = 0;
public static void main(String[] args) {
/*
* "Write a program that starts 10 jobs of random duration in 10 threads
* and prints out the order they finish in. Note that the jobs don't
* have to do anything, just sleep. You should probably define an
* instance variable to specify the order, which is defined when
* created."
*
*/
for (int i = 0; i < 10; i++) {
long sleepTime = (long) (Math.random() * 10000) + 1000;
Thread t = new Thread(new CustomJob(i, sleepTime));
t.start();
}
}
private static class CustomJob implements Runnable {
int jobId;
long sleepTime;
public CustomJob(int jobId, long sleepTime) {
this.jobId = jobId;
this.sleepTime = sleepTime;
count += 10;
}
public void run() {
try {
jobId += 1;
Thread.sleep(sleepTime);
System.out.format("Complete. Job %2d of %2s. I slept for %2d seconds.\n", jobId,
Thread.currentThread().getName(), sleepTime / 1000);
} catch (Exception e) {
System.out.println(Thread.currentThread().getName() + " was interrupted.");
e.printStackTrace();
}
}
}
}
/*
*Re-write ThreadsGuardedBlock.java
*utilizing ExecutorService objects.
*/
import java.util.concurrent.*;
public class ThreadsExecutorService {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
// submit each thread
for (int i = 0; i < 10; i++) {
executor.submit(new MyRunnable(i + 1));
}
executor.shutdown();
}
private static class MyRunnable implements Runnable {
private int numJobs;
public MyRunnable(int numJobs) {
this.numJobs = numJobs;
}
public void run() {
long sleepTime = (long) (Math.random() * 10000) + 1000;
try {
Thread.sleep(sleepTime);
System.out.format("Complete. Job number %2d of %16s. I slept for %2d seconds.\n", numJobs,
Thread.currentThread().getName(), sleepTime / 1000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " was interrupted.");
e.printStackTrace();
}
}
}
}
/*
*Re-write the TenThreads.java but only
*use two threads. Use the guarded block
*paradigm to acheive this.
*/
public class ThreadsGuardedBlock {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable(0));
thread.start();
Thread thread2 = new Thread(new MyRunnable(5));
thread2.start();
}
private static class MyRunnable implements Runnable {
private int numIterations;
private int numJobs;
public MyRunnable(int numJobs) {
numIterations = 0;
this.numJobs = numJobs;
}
public boolean isCountDone() {
if (numIterations == Integer.MIN_VALUE) {
return false;
}
return numIterations >= 5;
}
public void run() {
while (!isCountDone()) {
numIterations += 1;
numJobs += 1;
long sleepTime = (long) (Math.random() * 10000) + 1000;
try {
Thread.sleep(sleepTime);
System.out.format("Complete. Job number %2d of %2s. I slept for %2d seconds.\n", numJobs,
Thread.currentThread().getName(), sleepTime / 1000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " was interrupted.");
e.printStackTrace();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment