Sunday, September 22, 2013

Thinking in Java, Exercise Questions on Concurrency- I


/*Exercise 1:  Implement a Runnable.
 *  Inside run( ), print a message, and then call yield( ).
 *   Repeat this three times, and then return from run( ).
 *    Put a startup message in the constructor and a shutdown message when the task terminates.
 *    Create a number of these tasks and drive them using threads.
*/

import java.util.concurrent.*;
public class concurrency_ex1 {

public static void main(String[] args){
thRunnable1 r = new thRunnable1();
Thread a = new Thread(r);
Thread b = new Thread(r);

a.setName("Thread_a");
b.setName("Thread_b");
a.start();
b.start();
        }
}

public class thRunnable1 implements Runnable {

thRunnable1(){
System.out.println("Initialising the constructor...");
}

public void run(){
for(int i=0; i<3; i++) {
System.out.println("Inside run ..."+ i + "times" + " " + Thread.currentThread().getName());
Thread.yield();
}
System.out.println("Finishing the task : " + Thread.currentThread().getName());
}

}


/*Exercise 2: Following the form of generics/Fibonacci.java, create a task that produces a sequence of n Fibonacci numbers, 
 * where n is provided to the constructor of the task. Create a number of these tasks and drive them using threads.
 * 
 * */

import java.util.concurrent.*;
import java.util.*;

public class concurrency_ex2 {

public static void main(String args[]){
Thread a = new Thread(new thRunnable2(9));
Thread b = new Thread(new thRunnable2(19));
a.start();
b.start();
        }
}

public class thRunnable2 implements Runnable{
private int fib;
thRunnable2(int fib){
this.fib = fib;
}
public void run(){
int i=0, res = 1, j =0;
System.out.println("Thread is " + Thread.currentThread().getName());
while(res <= fib){
System.out.println(res);
j = res;
res = i + res;
i = j;
}
}
}

/*Exercise 3: Implement a Runnable.
 *  Inside run( ), print a message, and then call yield( ).
 *   Repeat this three times, and then return from run( ).
 *    Put a startup message in the constructor and a shutdown message when the task terminates. 
 *    Create using the different types of executors.
*/
import java.util.concurrent.*;

public class concurrency_ex1 {
public static void main(String[] args){
ExecutorService exec = Executors.newSingleThreadExecutor();
for(int i=0; i<10; i++)
exec.execute(new thRunnable1());
exec.shutdown();
}
}

public class thRunnable1 implements Runnable {
thRunnable1(){
System.out.println("Initialising the constructor...");
}
public void run(){
for(int i=0; i<3; i++) {
System.out.println("Inside run ..."+ i + "times" + " " + Thread.currentThread().getName());
Thread.yield();
}
System.out.println("Finishing the task : " + Thread.currentThread().getName());
}
}

/*Exercise 4: Following the form of generics/Fibonacci.java, create a task that produces a sequence of n Fibonacci numbers, 
 * where n is provided to the constructor of the task. Create using the different types of executors.
 * 
 * */

import java.util.concurrent.*;
import java.util.*;

public class concurrency_ex2 {

public static void main(String args[]){
ExecutorService exec = Executors.newFixedThreadPool(2);
exec.execute(new thRunnable2(9));
exec.execute((Runnable) new thRunnable2(16));
exec.execute((Runnable) new thRunnable2(7));
exec.shutdown(); 
}
}

public class thRunnable2 implements Runnable{
private int fib;
thRunnable2(int fib){
this.fib = fib;
}
public void run(){
int i=0, res = 1, j =0;
System.out.println("Thread is " + Thread.currentThread().getName());
while(res <= fib){
System.out.println(res);
j = res;
res = i + res;
i = j;
}
}
}

/* Exercise 5: Modify Exercise 2 so that the task is a Callable that sums the values of all the Fibonacci numbers.
 *  Create several tasks and display the results.
 * */

import java.util.concurrent.*;
import java.util.*;

public class concurrency_ex2 {

public static void main(String args[]){

                ExecutorService exec = Executors.newFixedThreadPool(2);
ArrayList<Future<Integer>> a = new ArrayList<Future<Integer>>();
a.add(exec.submit(new thCallable5(5)));
a.add(exec.submit(new thCallable5(8)));
a.add(exec.submit(new thCallable5(19)));
for(Future<Integer> fs: a){
try{
System.out.println("Sum is " +fs.get());
}catch(InterruptedException e){}
catch(ExecutionException ex){}
finally{
exec.shutdown();
}
}
}


import java.util.concurrent.*;

public class thCallable5 implements Callable<Integer>{
private int fib;
thCallable5(int fib){
this.fib = fib;
}
public Integer call(){
int i=0, res = 1, j =0, sum=0;
System.out.println("Thread is " + Thread.currentThread().getName());
while(res <= fib){
sum = sum + res;
System.out.println(res);
j = res;
res = i + res;
i = j;
}
return sum;
}
}


/* Exercise 6 : Create a task that sleeps for a random amount of time between 1 and 10 seconds, 
 * then displays its sleep time and exits.
 *  Create and run a quantity (given on the command line) of these tasks.*/

import java.util.concurrent.*;
import java.util.*;


public class concurrency_ex6 {
public static void main(String args[]){
ExecutorService exec = Executors.newCachedThreadPool();
Scanner sc = new Scanner(System.in);
int task = sc.nextInt();
 
for(int i=0; i<task; i++){
Future<Integer> sleep_t = exec.submit(new thCallable6());
try{
System.out.println(sleep_t.get());
}catch(InterruptedException e){}
catch(ExecutionException ex){}
}
}
}

import java.util.concurrent.*;
import java.util.Random;
public class thCallable6 implements Callable<Integer>{
public Random r = new Random();
public Integer call(){
int sleep_t = r.nextInt(10);
try{
Thread.sleep(sleep_t * 1000);
}catch(InterruptedException e) {
System.out.println(e);
}
return sleep_t;
}