DS Lab Manual

Preview:

Citation preview

AIM:To write a java program for implementing Breadth First Search Algorithm.

ALGORITHM:Step 1:Start the program.Step 2:Initialize all vertices to the ready state.Step 3: Put the starting vertex A in queue and change the status of A in waiting state.Step 4: Repeat the step until queue is empty.Step 5: Examine each neighbor j of N

i. If status j=1(Ready state).add j in near of queue and reset the status. ii. Unstate j=2 (Waiting State or Processed state)

Step 6:Finally the processed or accessed node will be displayed.Step 7:Stop the program.

CODING:import java.io.*;class bfs1{public static void main(String args[]) throws IOException{

int i,n,j,k;System.out.println("No. of vertices :") ; BufferedReader br= new BufferedReader (new InputStreamReader(System.in));n =Integer.parseInt(br.readLine());int q[] = new int[10];int m[] = new int[10];int a[][] = new int[10][10];for (i=0; i<10; i++){

m[i] = 0;}System.out.println("\n\nEnter 1 if edge is present, 0 if not");for (i=0; i<n; i++){

System.out.println("\n");for (j=i; j<n; j++){

System.out.println("Edge between " + (i+1) + " and " + (j+1)+ ":" );a[i][j]=Integer.parseInt(br.readLine());a[j][i]=a[i][j];

}a[i][i]=0;

}System.out.println("\nOrder of accessed nodes : \n");q[0] = 0; m[0] = 1;

EX.NO: 1a IMPLEMENTATION OF BREADTH FIRST SEARCH ALGORITHM

int u; int node=1; int beg1=1, beg=0; while(node>0) { u=q[beg];beg++; System.out.println(" " +(u+1)); node--; for(j=0;j<n;j++) { if(a[u][j]==1) { if(m[j]==0) { m[j]=1; q[beg1]=j; node++;

beg1++; } } } } } }OUTPUT:C:\>java\jdk1.7.0\bin>javac bfs1.javaC:\>java\jdk1.7.0\bin>java bfs1No of vertices: 6Enter 1 if edge is present, 0 if notEdge between 1 & 1:0Edge between 1 & 2:1Edge between 1 & 3:1Edge between 1 & 4:0Edge between 1 & 5:1Edge between 1 & 6:0Edge between 2 & 2:0Edge between 2 & 3:0Edge between 2 & 4:0Edge between 2 & 5:0Edge between 2 & 6:1

Edge between 3 & 3:0Edge between 3 & 4:1Edge between 3 & 5:0Edge between 3 & 6:0Edge between 4 & 4:0

Edge between 4 & 5:1Edge between 4 & 6:1

Edge between 5 & 5:0Edge between 5 & 6:1

Edge between 6 & 6:0Order of accessed nodes: 123564

RESULT:Thus the java program for Breadth First Search Algorithm has been executed

successfully.

EX.NO: 1b IMPLEMENTATION OF DEPTH FIRST SEARCH ALGORITHM

AIM:To write a java program for implementing Depth First Search Algorithm.

ALGORITHM:Step 1:Start the program.Step 2:Initialize all vertices to the ready state.Step 3:If edge is present give it as 1.if not present then give it as zeroStep 4:Put the starting vertex A in Stack and change the status of A in waiting state.Step 5:Repeat the step until Stack is empty.Step 6:Finally the processed or accessed node will be displayed.Step 7:Stop the program.CODING:import java.io.*; class dfs { static void dfs(int a[][], int m[], int i, int n) { int j; System.out.println("\t" + (i+1)); m[i] = 1; for(j=0; j<n; j++) if(a[i][j]==1 && m[j]==0) dfs(a,m,j,n); }

public static void main(String args[]) throws IOException { int n, i, j; System.out.println("No. of vertices : "); BufferedReader br= new BufferedReader (new InputStreamReader(System.in)); n =Integer.parseInt(br.readLine()); int m[]= new int[n]; int a[][] = new int[n][n]; for (i=0; i<n; i++) { m[i] = 0; } System.out.println("\n\nEnter 1 if edge is present, 0 if not"); for (i=0; i<n; i++) { System.out.println("\n"); for (j=i; j<n; j++) { System.out.println("Edge between " + (i+1) + " and " + (j+1)+ " : "); a[i][j] =Integer.parseInt(br.readLine()); a[j][i]=a[i][j]; } a[i][i] = 0; } System.out.println("\nOrder of accessed nodes : \n"); for (i=0; i<n; i++) if (m[i]==0) dfs(a,m,i,n); } } OUTPUT:C:\>java\jdk1.7.0\bin>javac dfs.javaC:\>java\jdk1.7.0\bin>java dfsNo of vertices: 5Enter 1 if edge is present, 0 if notEdge between 1 & 1:0Edge between 1 & 2:1Edge between 1 & 3:0Edge between 1 & 4:0Edge between 1 & 5:0

Edge between 2 & 2:0Edge between 2 & 3:1Edge between 2 & 4:0Edge between 2 & 5:1

Edge between 3 & 3:0Edge between 3 & 4:1Edge between 3 & 5:1Edge between 4 & 2:1Edge between 4 & 3:1Edge between 4 & 4:0Edge between 4 & 5:0Edge between 5 & 3:1Edge between 5 & 4:0Edge between 5 & 5:0Order of accessed nodes: 12435

RESULT:Thus the java program for Depth First Search Algorithm has been executed successfully.

EX.NO: 1c IMPLEMENTATION OF DIJIKSTRA’S SINGLE SOURCE SHORTEST PATH ALGORITHM

AIM:To write a java program to implement the dijikstra's single source shortest path

algorithm.

ALGORITHM:Step 1: Start the program.Step 2: Import the java packages and declare the necessary variables.Step 3: Construct a graph with vertices and path between vertices with its corresponding

weight.Step 4: Label the starting node with a 0.Step 5: For each edge connecting to the starting node and choose the edge with least

value.Step 6: Repeat steps 4 & 5 until the node you are trying to reach (the destination node) .Step 7: Retrace the shortest route backwards through the network back to your start node.

You've found the path of least weight.Step 8: Then,print the shortest path of the graph .Step 9: Stop the program.

CODING:import java.io.*;import java.util.*;class graph

{ int v,e,w,a,b;int d[],p[],visited[];int m[][];void creategraph(){Scanner kbd=new Scanner(System.in);System.out.println("Enter the no.of nodes:");v=kbd.nextInt();System.out.println("Enter the no.of paths:");e=kbd.nextInt();m=new int[v+1][v+1];for(int i=1;i<=v;i++){for(int j=1;j<=v;j++)m[i][j]=0;}for(int i=1;i<=e;i++){System.out.println("Enter node 1:");a=kbd.nextInt();System.out.println("Enter node 2:");b=kbd.nextInt();System.out.println("Enter weight:");w=kbd.nextInt();m[a][b]=m[b][a]=w;}for(int i=1;i<=v;i++){for(int j=1;j<=v;j++)System.out.println(m[i][j]+"");System.out.println();}}void calldj(){d=new int[v+1];p=new int[v+1];visited=new int[v+1];for(int i=1;i<=v;i++){p[i]=visited[i]=0;}for(int i=1;i<=v;i++){d[i]=32762;}di();

}void di(){ int current,dest,source;Scanner kbd=new Scanner(System.in);System.out.println("Enter the destination:");dest=kbd.nextInt();current=1;visited[current]=1;d[current]=0;while(current!=dest){ int dc=d[current];for(int i=1;i<=v;i++){ if(m[current][i]!=0&& visited[i]!=1){ if(m[current][i]+dc<d[i]){d[i]=m[current][i]+dc;p[i]=current;}}} int min=32762;for(int i=1;i<=v;i++){ if(visited[i]!=1&& d[i]<min){min=d[i];current=i;}}visited [current]=1;}System.out.println("shortest path is:"+d[dest]);}} class dij{public static void main(String args[]){graph g=new graph();g.creategraph();g.calldj();}}

OUTPUT:C:\Documents and Settings\Administrator\Desktop>javac dij.javaC:\Documents and Settings\Administrator\Desktop>java dij

Graph:1

2 86

3 7 9

Enter the no.of nodes: 5Enter the no.of paths: 6Enter node 1: 1Enter node 2: 2Enter weight: 2Enter node 1: 2Enter node 2: 4Enter weight: 3Enter node 1: 1Enter node 2: 5Enter weight: 6Enter node 1: 5Enter node 2: 4Enter weight: 7Enter node 1: 1Enter node 2: 3Enter weight: 8Enter node 1: 3Enter node 2: 4Enter weight: 902806

20030

80090

2

4

35

03907

60070Enter the destination: 4shortest path is: 5

RESULT:

Thus, the java program for Dijikstra’s single source shortest path algorithm has been implemented and executed.

EX.NO: 2a IMPLEMENTATION OF NETWORK FLOW PROBLEM

AIM: To write a java program for the implementation of Network flow problem using max-flow and min-cut theorem.

ALGORITHM:Step 1: Start the process.Step 2: Import the necessary packages.Step 3: Declare the class Network Flow Problem and declare the various variable used.Step 4: Declare a constructor and method of BFS.Step 5: Declare the method NF(), which takes the graph source and destination node as input.Step 6: The NF() produces flow graph and residual graph as its output.Step 7: Declare the print() which prints min-cut for network.Step 8: Declare the main method, which gets the graph matrix as input from user.Step 9: Print max-flow and min-cut as output for given graph.Step 10: Stop the process.

CODING:import java.util.ArrayList;import java.util.HashSet;import java.util.Iterator;import java.util.LinkedList;import java.util.Queue;

import java.util.Scanner;import java.util.Set;public class NetworkFlowProb{private int[] parent;private Queue<Integer> queue;private int numberOfVertices;private boolean[] visited;private Set<Pair> cutSet;private ArrayList<Integer> reachable;private ArrayList<Integer> unreachable;public NetworkFlowProb (int numberOfVertices){this.numberOfVertices = numberOfVertices;this.queue = new LinkedList<Integer>();parent = new int[numberOfVertices + 1];visited = new boolean[numberOfVertices + 1];cutSet = new HashSet<Pair>();reachable = new ArrayList<Integer>();unreachable = new ArrayList<Integer>();}public boolean bfs (int source, int goal, int graph[][]){boolean pathFound = false;int destination, element;for (int vertex = 1; vertex <= numberOfVertices; vertex++){parent[vertex] = -1;visited[vertex] = false;}queue.add(source);parent[source] = -1;visited[source] = true;while (!queue.isEmpty()){element = queue.remove();destination = 1;while (destination <= numberOfVertices){if (graph[element][destination] > 0 && !visited[destination]){parent[destination] = element;queue.add(destination);visited[destination] = true;}destination++;

}}if (visited[goal]){pathFound = true;}return pathFound;}public int networkFlow (int graph[][], int source, int destination){int u, v;int maxFlow = 0;int pathFlow;int[][] residualGraph = new int[numberOfVertices + 1][numberOfVertices + 1];for (int sourceVertex = 1; sourceVertex <= numberOfVertices; sourceVertex++){for (int destinationVertex = 1; destinationVertex <= numberOfVertices; destinationVertex++){residualGraph[sourceVertex][destinationVertex] = graph[sourceVertex][destinationVertex];}}while (bfs(source, destination, residualGraph)){pathFlow = Integer.MAX_VALUE;for (v = destination; v != source; v = parent[v]){u = parent[v];pathFlow = Math.min(pathFlow, residualGraph[u][v]);}for (v = destination; v != source; v = parent[v]){u = parent[v];residualGraph[u][v] -= pathFlow;residualGraph[v][u] += pathFlow;}maxFlow += pathFlow;}for (int vertex = 1; vertex <= numberOfVertices; vertex++){if (bfs(source, vertex, residualGraph)){reachable.add(vertex);}else{unreachable.add(vertex);

}}for (int i = 0; i < reachable.size(); i++){for (int j = 0; j < unreachable.size(); j++){if (graph[reachable.get(i)][unreachable.get(j)] > 0){cutSet.add (new Pair(reachable.get(i), unreachable.get(j)));}}}return maxFlow;}public void printCutSet (){Iterator<Pair> iterator = cutSet.iterator();while (iterator.hasNext()){Pair pair = iterator.next();System.out.println(pair.source + "-" + pair.destination);}}public static void main (String...arg){int[][] graph;int numberOfNodes;int source;int sink;int maxFlow;Scanner scanner = new Scanner(System.in);System.out.println("Enter the number of nodes");numberOfNodes = scanner.nextInt();graph = new int[numberOfNodes + 1][numberOfNodes + 1];System.out.println("Enter the graph matrix");for (int sourceVertex = 1; sourceVertex <= numberOfNodes; sourceVertex++){for (int destinationVertex = 1; destinationVertex <= numberOfNodes; destinationVertex++){graph[sourceVertex][destinationVertex] = scanner.nextInt();}}System.out.println("Enter the source of the graph");source= scanner.nextInt();System.out.println("Enter the sink of the graph");sink = scanner.nextInt();

NetworkFlowProb networkFlowProb = new NetworkFlowProb(numberOfNodes);maxFlow = networkFlowProb.networkFlow(graph, source, sink);System.out.println("The Max flow in the graph is " + maxFlow);System.out.println("The Minimum Cut Set in the Graph is ");networkFlowProb.printCutSet();scanner.close();}}class Pair{public int source;public int destination;public Pair(int source, int destination){this.source = source;this.destination = destination;}public Pair(){}}OUTPUT:C:\Users\Admin>javac NetworkFlowProb.javaC:\Users\Admin>java NetworkFlowProbEnter the number of nodes: 5Enter the graph matrix0 20 31 0 01 0 0 21 00 2 0 30 00 0 0 0 750 0 0 0 0Enter the source of the graph 1Enter the sink of the graph5The Max flow in the graph is 51The Minimum Cut Set in the Graph is1-31-2RESULT: Thus the java program for implementation of Network flow problem using max-flow min-cut theorem has been executed and output was verified successfully.

EX.NO:3a IMPLEMENTATION OF HILL CLIMBING ALGORITHM USING ELEVATOR PROBLEM

AIM:To implement hill climbing algorithm using the elevator problem using Java

Program.

ALGORITHM:Step 1: Start the program.Step 2: Create class as elevator with functions optimize_floors() floors_walked(),reconstruct_path() and print_matrix().Step 3: Get floor to reach as an input.Step 4: Finally find the path between floors, each floor is considered as small local maximum. Step 5: Calculate cost for reaching the destination.Step 6: End the program.

CODING:import java.util.*;class elevator{

static final int NFLOORS = 25;static final int MAX_RIDERS = 50;static final int MAXINT = 100007;static int stops[] = new int [MAX_RIDERS];static int nriders, nstops;static int m[][] = new int [NFLOORS+1][MAX_RIDERS];static int p[][] = new int [NFLOORS+1][MAX_RIDERS];

static int optimize_floors(){

int cost,laststop;for(int i=0;i<=NFLOORS;i++){

m[i][0]=floors_walked(0,MAXINT);p[i][0]=-1;

}for(int j=1;j<=nstops;j++)

for(int i=0;i<=NFLOORS;i++){

m[i][j]=MAXINT;for(int k=0;k<=i;k++){

cost=m[k][j-1]-floors_walked(k,MAXINT)+floors_walked(k,i)+floors_walked(i,MAXINT);if(cost<m[i][j]){

m[i][j]=cost;p[i][j]=k;

}}

}laststop = 0;for(int i=1;i<=NFLOORS;i++)

if(m[i][nstops]<m[laststop][nstops])laststop = i;

return laststop;}

static int floors_walked(int previous,int current){

int nsteps=0;for(int i=1;i<=nriders;i++)

if(stops[i]>previous&&stops[i]<=current)nsteps+=Math.min(stops[i]-previous, current-stops[i]);

return nsteps;}

static void reconstruct_path(int lastfloor, int stops_to_go){

if (stops_to_go > 1)reconstruct_path( p[lastfloor][stops_to_go], stops_to_go-1);

System.out.printf("%d\n",lastfloor);}

static void print_matrix(int m[][]){

for (int j=0; j<=nstops; j++){

for (int i=0; i<=NFLOORS; i++)System.out.printf("%3d",m[i][j]);

System.out.printf("\n");}

}

static public void main(String[] args){

int laststop;Scanner sc = new Scanner(System.in);nriders = sc.nextInt();nstops = sc.nextInt();for (int i=1; i<=nriders; i++)

stops[i] = sc.nextInt();for (int i=1; i<=nriders; i++)

System.out.printf("%d\n",stops[i]);laststop = optimize_floors();print_matrix(m);System.out.printf("\n");print_matrix(p);System.out.printf("cost = %d\n",m[laststop][nstops]);reconstruct_path(laststop,nstops);

}}OUTPUT:C:\Users\Admin>javac elevator.javaC:\Users\Admin>java elevator

123 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

3 2 1 0 1 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3

3 2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3Cost=003RESULT: Thus the java program for hill climbing algorithm using the elevator problem has been executed and output was verified successfully.

EX.NO: 3b IMPLEMENTATION OF ALGORITHMS USING DYNAMIC PROGRAMMINGDESIGN TECHNIQUES

AIM:To write a java program for implementing dynamic programming concept using longest

common subsequnce.

ALGORITHM:Step 1:Start the program.Step 2:Enter the String 1 and String 2 for the comparison.Step 3:Calculate the length of the String using length () for both String.Step 4:Compare String 1 and String 2 using compare () string syntax.

Step 5:By implementing the value of both m and n compare each character in String.Step 6:Finally display the output as common String.Step 7:Stop the program.

CODING:import java.io.*; import java.lang.*; class lcs { public static void main(String args[]) throws IOException { int i,j,k,m,n; BufferedReader br= new BufferedReader (new InputStreamReader(System.in)); System.out.println("Enter the 1st string "); String x=br.readLine(); System.out.println("Enter the 2nd string "); String y=br.readLine(); m=x.length(); n=y.length(); int l[][]=new int[m+1][n+1]; for(i=0;i<=m;i++) l[i][0]=0; for (j=1;j<=n;j++) l[0][j]=0; for (i=1;i<=m;i++) { for (j=1;j<=n;j++) { if (x.charAt(i-1)==y.charAt(j-1)) l[i][j]=l[i-1][j-1] + 1; else if((l[i-1][j]>l[i][j-1])) l[i][j]=l[i-1][j]; else l[i][j]=l[i][j-1]; } } char common[]=new char[l[m][n]]; for (k=0,i=m,j=n; i>0 && j>0;) { if (x.charAt(i-1)==y.charAt(j-1)) { common[k++] = x.charAt(i-1); i--;

j--; } else if(l[i-1][j] >= l[i][j-1]) i--; else j--; } String common1 = new String(common); StringBuffer common2 = new StringBuffer(common1); System.out.println("the longest common subsequence is "+common2.reverse()); } } OUTPUT:Enter the 1st StringAnithaEnter the 2nd StringSusheelaLongest Common Subsequence is haRESULT:

Thus the program for implementing dynamic programming concept using longest common subsequence is executed successfully and the output is achieved.

EX.NO: 4 IMPLEMENTATION OF RECURSIVE BACKTRACKING ALGORITHM USING N-QUEENS PROBLEM

AIM:To write a java program to implement recursive backtracking algorithm by N-Queens

problem.

ALGORITHM:Step 1: Start the program.Step 2: Import the java packages and declare the necessary variables.Step 3: Get the number of queens to be placed.Step 4: Implement the function “enumerate” which recursively backtracks and places the queens.Step 5: Check that Queens should not be placed in same row, same column and in same diagonal.Step 6: Print the all possible solutions.Step 7: Stop the program.

CODING:import java.io.*;public class Queens{

public static boolean isConsistent(int[] q,int n){

for(int i=0;i<n;i++){

if(q[i]==q[n])return false;

if((q[i]-q[n])==(n-i))return false;

if((q[n]-q[i])==(n-i))return false;

}return true;

}public static void printQueens(int[] q)

{ int N=q.length;for(int i=0;i<N;i++){

for(int j=0;j<N;j++){ if(q[i]==j)System.out.print("Q");elseSystem.out.print("*");}System.out.println();

}System.out.println();

}

public static void enumerate1(int N){ int[]a=new int[N];enumerate(a,0);}

public static void enumerate(int[]q,int n){ int N=q.length;if(n==N)

printQueens(q);else

{for(int i=0;i<N;i++)

{

q[n]=i;if(isConsistent(q,n))enumerate(q,n+1);}

}}

public static void main(String[]args)throws IOException{ System.out.printf("Enter the Number of Queens:");

BufferedReader br= new BufferedReader(new InputStreamReader(System.in));int N = Integer.parseInt(br.readLine());enumerate1(N);}

}

OUTPUT:Enter the Number of Queens: 4

* Q * ** * * Q Q * * ** * Q ** * Q *Q * * ** * * Q* Q * *

RESULT:Thus, the java program for N-Queens problem using recursive backtracking algorithm

has been executed successfully.

EX.NO: 5 IMPLEMENTATION OF RANDOMIZED ALGORITHMS USING PRIMALITY TESTING

AIM: To write a java program for the implementation of Randomized algorithms using Primality Testing .

ALGORITHM:Step 1: Start the process.Step 2: Import the necessary packages and declare the variables needed.Step 3: Declare the constructors for the Random class which computes value for a temporary state.Step 4: Declare the class primality and its method,

1.1 If value of I is 0 then return 1.1.2 Assign X is equal to (a,i/2,n) if x is 0 then return o.1.3 Assign y is equal to (x*x) %n, where y is 1, x not equal to 1 to n-1,

then return 0.1.4 If i/2 not equal two, then assign y to a*y*n,return y.

Step 5: Check whether the number is generated are not.Step 6: If it is prime, print it as output.Step 7: Stop the process.

CODING:import java.io.*;import java.util.*;class Random{private static final int A = 48271;private static final int M = 2147483647;private static final int Q = M / A;private static final int R = M % A;int state;public Random( ){this( (int) ( System.currentTimeMillis( ) % Integer.MAX_VALUE ) );}public Random( int initialValue ){if( initialValue < 0 )initialValue += M;state = initialValue;if( state <= 0 )state = 1;}public int randomInt( ){int tmpState = A * ( state % Q ) - R * ( state / Q );if( tmpState >= 0 )state = tmpState;elsestate = tmpState + M;return state;}public long randomLong( long low, long high ){long longVal = ( (long) randomInt( ) << 31 ) + randomInt( );long longM = ( (long) M << 31 ) + M;double partitionSize = (double) longM / ( high - low + 1 );return (long) ( longVal / partitionSize ) + low;}}class Primality

{private static long witness( long a, long i, long n ){if( i == 0 )return 1;long x = witness( a, i / 2, n );if( x == 0 ) return 0;long y = ( x * x ) % n;if( y == 1 && x != 1 && x != n - 1 )return 0;if( i % 2 != 0 )y = ( a * y ) % n;return y;}public static final int TRIALS = 5;public static boolean isPrime( long n ){Random r = new Random( );for( int counter = 0; counter < TRIALS; counter++ )if( witness( r.randomLong ( 2, n - 2 ), n - 1, n ) != 1 )return false;return true;}public static void main( String [ ] args ){for( int i = 101; i < 200; i += 2 )if( isPrime( i ) )System.out.println( i + " is prime" );}

OUTPUT:C:\Java\jdk1.6\bin >java Primality101 is prime103 is prime107 is prime109 is prime113 is prime127 is prime131 is prime137 is prime139 is prime149 is prime151 is prime157 is prime163 is prime

167 is prime173 is prime179 is prime181 is prime191 is prime193 is prime197 is prime199 is primeRESULT: Thus the java program for Randomized algorithm using Primality Testing has been executed and output was verified successfully.

EX.NO:6a IMPLEMENTATION OF CONCURRENT QUEUE USING PRODUCER-CONSUMER PROBLEM

AIM:

To write a java program for the implementation of concurrent queue using Producer-Consumer Problem.

ALGORITHM:

Step 1: Start the program.Step 2: Import the necessary packages and declare the necessary variables.Step 3: Class prod which extends thread and declare a run() which print the produced item.Step 4: Declare the main method and create object for each thread.Step 5: Invoke the threads.Step 6: Print the output.Step 7: Stop the process.

CODING:

import java.util.*;import java.io.*;public class ConsumerProducer {public static void main (String [] args) {Buffer buf = new Buffer();Thread prod = new Producer(10, buf);Thread cons = new Consumer(10, buf);prod.start();cons.start();try {prod.join();cons.join();

} catch (InterruptedException e) {return;}}}class Buffer {private int contents;private boolean empty = true;public synchronized void put (int i) throws InterruptedException {while (empty == false) {try { wait(); }catch (InterruptedException e) {throw e;}}contents = i;empty = false;System.out.println("Producer: put..." + i);notify();}public synchronized int get () throws InterruptedException {while (empty == true) {try { wait(); }catch (InterruptedException e) {throw e;}}empty = true;notify();int val = contents;System.out.println("Consumer: got..." + val);return val;}}class Producer extends Thread {private int n;private Buffer prodBuf;public Producer (int m, Buffer buf) {n = m;prodBuf = buf;}public void run() {for (int i = 0; i < n; i++) {try {Thread.sleep( (int) Math.random() * 10);} catch (InterruptedException e) {return;}try {prodBuf.put(i + 1); //starting from 1, not 0} catch (InterruptedException e) {return;}}}}

class Consumer extends Thread {private int n;private Buffer consBuf;public Consumer (int m, Buffer buf) {n = m;consBuf = buf;}

public void run() {int value;for (int i = 0; i < n; i++) {try {value = consBuf.get();} catch (InterruptedException e) {return;}try {Thread.sleep( (int) Math.random() * 100);} catch (InterruptedException e) {return;}}}}

OUTPUT:

C:\Users\admin\Desktop>javac ConsumerProducer.javaC:\Users\admin\Desktop>java ConsumerProducerProducer: put...1Consumer: got...1Producer: put...2Consumer: got...2Producer: put...3Consumer: got...3Producer: put...4Consumer: got...4Producer: put...5Consumer: got...5Producer: put...6Consumer: got...6Producer: put...7Consumer: got...7Producer: put...8Consumer: got...8Producer: put...9Consumer: got...9Producer: put...10Consumer: got...10RESULT :

Thus, the java program for Producer-Consumer problem has been implemented and output was verified successfully.

EX.NO: 6b IMPLEMENTATION OF CONCURRENT STACKS USING VARIOUS LOCKING AND SYNCHRONIZATION MECHANISMS

AIM: To write a java program for the implementation of concurrent stacks using various locking and synchronization mechanisms.

ALGORITHM:

Step 1: Start the Program.Step 2:Declare the variables needed.Step 3:Declare the necessary functions stackimpl(),isempty(),isfull(),push(),pop().Step 4: Perform the synchronization to the stack created.Step 5: Stop the Program.

CODING:import java.util.*;import java.io.*;class StackImpl { private Object[] stackArray; private int topOfStack;

public StackImpl(int capacity) { stackArray = new Object[capacity]; topOfStack = -1; }

public synchronized boolean push(Object element) { if (isFull()) return false; ++topOfStack; try { Thread.sleep(1000); } catch (Exception e) { } stackArray[topOfStack] = element; return true; }

public synchronized Object pop() { if (isEmpty()) return null; Object obj = stackArray[topOfStack]; stackArray[topOfStack] = null; try { Thread.sleep(1000); } catch (Exception e) { } topOfStack--; return obj; }

public boolean isEmpty() { return topOfStack < 0; } public boolean isFull() { return topOfStack >= stackArray.length - 1; }}public class Mutex { public static void main(String[] args) {

final StackImpl stack = new StackImpl(20);

(new Thread("Pusher") { public void run() { for(;;) { System.out.println("Pushed: " + stack.push(2008)); } } }).start();

(new Thread("Popper") { public void run() { for(;;) { System.out.println("Popped: " + stack.pop()); } } }).start();

System.out.println("Exit from main()."); }}

OUTPUT:Exit from main ().Popped: nullPopped: nullPopped: nullPushed: truePopped: 2008Pushed: truePopped: 2008Pushed: truePopped: 2008RESULT :

Thus, the java program for various locking and synchronization mechanisms has been implemented and output was verified successfully.

AIM:

EX.NO: 7 DEVELOP A SIMPLE APPLICATIONS INVOLVING CONCURRENCY

To write a java program to develop a simple applications involving concurrency.

ALGORITHM:Step 1: Start the program.Step 2: Import the necessary packages and declare the variables needed.Step 3: Declare the class MyCollection.Step 4: Declare a synchronized method remove() to remove element from the list.Step 5: Declare a synchronized method add() to end our element to the list.Step 6: Declare the class my class which randomly display the process .Step 7: Declare the class which has main method to invoke different threads.Step 8: Stop the program.

CODING :

import java.util.*;class MyCollection{private List<Integer> buffer= new ArrayList<Integer>(400);public synchronized Integer remove(){int c;while (buffer.size() == 0) {try {this.wait();System.out.println("Waiting or new numbers to be pushed");} catch (InterruptedException e) {}}c = buffer.remove(buffer.size()-1);return c;}public synchronized void add(int x) {this.notify();buffer.add(x);}public synchronized void show(){

System.out.println(buffer);}}class MyProcess implements Runnable{private MyCollection col;private int num;private static int counter = 1;public MyProcess (MyCollection s) {col = s;num = counter++;}public void run() {for (;;){System.out.println("MyProcess ID : " + num);int y=(int)(Math.random()*10)/3;if(y==1){col.remove();}else if(y==2){col.add((int)(Math.random()*10));}else{col.show();}try{Thread.sleep((int)(Math.random() * 300));} catch (InterruptedException e){}}}}public class SyncTest1{public static void main(String[] args){MyCollection ds = new MyCollection();MyProcess p1 = new MyProcess(ds);

Thread tp1 = new Thread (p1);tp1.start();MyProcess p2 = new MyProcess(ds);Thread tp2 = new Thread (p2);tp2.start();MyProcess p3 = new MyProcess(ds);Thread tp3 = new Thread (p3);tp3.start();MyProcess p4 = new MyProcess(ds);Thread tp4 = new Thread (p4);tp4.start();}}OUTPUT:

C:\Users\Admin>java SyncTest1MyProcess ID : 1MyProcess ID : 2MyProcess ID : 3MyProcess ID : 4[1, 1, 5]MyProcess ID : 1MyProcess ID : 1MyProcess ID : 3[1]MyProcess ID : 2MyProcess ID : 4MyProcess ID : 4MyProcess ID : 1MyProcess ID : 3Waiting or new numbers to be pushedMyProcess ID : 2[]MyProcess ID : 4MyProcess ID : 4MyProcess ID : 3MyProcess ID : 2[]MyProcess ID : 1Waiting or new numbers to be pushedMyProcess ID : 4MyProcess ID : 2Waiting or new numbers to be pushedMyProcess ID : 3MyProcess ID : 4Waiting or new numbers to be pushed

MyProcess ID : 1[]MyProcess ID : 4MyProcess ID : 1[]MyProcess ID : 2MyProcess ID : 3[]MyProcess ID : 3[]MyProcess ID : 1[]MyProcess ID : 3[]MyProcess ID : 1Waiting or new numbers to be pushedMyProcess ID : 4Waiting or new numbers to be pushedMyProcess ID : 2[]MyProcess ID : 1[]MyProcess ID : 3MyProcess ID : 1MyProcess ID : 2Waiting or new numbers to be pushedMyProcess ID : 4MyProcess ID : 2[]MyProcess ID : 3Waiting or new numbers to be pushedMyProcess ID : 3MyProcess ID : 2Waiting or new numbers to be pushedMyProcess ID : 1MyProcess ID : 4[]MyProcess ID : 2MyProcess ID : 4[]MyProcess ID : 4[]MyProcess ID : 4[]MyProcess ID : 4[]

MyProcess ID : 4Waiting or new numbers to be pushedMyProcess ID : 4[]MyProcess ID : 3Waiting or new numbers to be pushedMyProcess ID : 4[]MyProcess ID : 4Waiting or new numbers to be pushedMyProcess ID : 4[]MyProcess ID : 3MyProcess ID : 1[9]MyProcess ID : 2MyProcess ID : 3MyProcess ID : 2MyProcess ID : 4[]MyProcess ID : 1[]MyProcess ID : 4[]MyProcess ID : 4Waiting or new numbers to be pushedMyProcess ID : 4Waiting or new numbers to be pushedMyProcess ID : 3[]MyProcess ID : 1MyProcess ID : 4Waiting or new numbers to be pushedMyProcess ID : 1[]MyProcess ID : 2MyProcess ID : 3MyProcess ID : 2MyProcess ID : 4MyProcess ID : 3MyProcess ID : 1[]MyProcess ID : 1Waiting or new numbers to be pushedMyProcess ID : 2MyProcess ID : 1

Waiting or new numbers to be pushedMyProcess ID : 4[]MyProcess ID : 1MyProcess ID : 4[]MyProcess ID : 4

RESULT: Thus the java program for develop a simple applications involving concurrency has been implemented and output was verified successfully.