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.java C:\>java\jdk1.7.0\bin>java bfs1 No of vertices: 6 Enter 1 if edge is present, 0 if not Edge between 1 & 1:0 Edge between 1 & 2:1 Edge between 1 & 3:1 Edge between 1 & 4:0 Edge between 1 & 5:1 Edge between 1 & 6:0 Edge between 2 & 2:0 Edge between 2 & 3:0 Edge between 2 & 4:0 Edge between 2 & 5:0 Edge between 2 & 6:1
Edge between 3 & 3:0 Edge between 3 & 4:1 Edge between 3 & 5:0 Edge between 3 & 6:0 Edge between 4 & 4:0 Edge between 4 & 5:1 Edge between 4 & 6:1
Edge between 5 & 5:0 Edge between 5 & 6:1
Edge between 6 & 6:0 Order of accessed nodes: 1 2 3 5 6 4
RESULT: Thus the java program for Breadth First Search Algorithm has been executed successfully.
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 zero Step 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); }
EX.NO: 1b
IMPLEMENTATION OF DEPTH FIRST SEARCH ALGORITHM 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.java C:\>java\jdk1.7.0\bin>java dfs No of vertices: 5 Enter 1 if edge is present, 0 if not Edge between 1 & 1:0 Edge between 1 & 2:1 Edge between 1 & 3:0 Edge between 1 & 4:0 Edge between 1 & 5:0
Edge between 2 & 2:0 Edge between 2 & 3:1 Edge between 2 & 4:0 Edge between 2 & 5:1 Edge between 3 & 3:0 Edge between 3 & 4:1 Edge between 3 & 5:1 Edge between 4 & 2:1 Edge between 4 & 3:1 Edge between 4 & 4:0 Edge between 4 & 5:0 Edge between 5 & 3:1 Edge between 5 & 4:0 Edge between 5 & 5:0 Order of accessed nodes: 1 2 4 3 5
RESULT: Thus the java program for Depth First Search Algorithm has been executed successfully.
EX.NO: 1c
IMPLEMENTATION OF DIJIKSTRAS 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.
OUTPUT: C:\Documents and Settings\Administrator\Desktop>javac dij.java C:\Documents and Settings\Administrator\Desktop>java dij
Graph:
2 8 6
3 7 9
Enter the no.of nodes: 5 Enter the no.of paths: 6 Enter node 1: 1 Enter node 2: 2 Enter weight: 2 Enter node 1: 2 Enter node 2: 4 Enter weight: 3 Enter node 1: 1 Enter node 2: 5 Enter weight: 6 Enter node 1: 5 Enter node 2: 4 Enter weight: 7 Enter node 1: 1 Enter node 2: 3 Enter weight: 8 Enter node 1: 3 Enter node 2: 4 Enter weight: 9 0 2 8 0 6
2 0 0 3 0
8 0 0 9 2 1 4 3 5 0
0 3 9 0 7
6 0 0 7 0 Enter the destination: 4 shortest path is: 5 RESULT:
Thus, the java program for Dijikstras 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.java C:\Users\Admin>java NetworkFlowProb Enter the number of nodes: 5 Enter the graph matrix 0 20 31 0 0 1 0 0 21 0 0 2 0 30 0 0 0 0 0 75 0 0 0 0 0 Enter the source of the graph 1 Enter the sink of the graph 5 The Max flow in the graph is 51 The Minimum Cut Set in the Graph is 1-3 1-2 RESULT: Thus the java program for implementation of Network flow problem using max-flow min-cut theorem has been executed and output was verified successfully.
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;
EX.NO:3a IMPLEMENTATION OF HILL CLIMBING ALGORITHM USING ELEVATOR PROBLEM
-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 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 Cost=0 0 3 RESULT: 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 PROGRAMMING DESIGN 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 1 st String Anitha Enter the 2 nd String Susheela Longest Common Subsequence is ha RESULT: Thus the program for implementing dynamic programming concept using longest common subsequence is executed successfully and the output is achieved.
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
EX.NO: 4 IMPLEMENTATION OF RECURSIVE BACKTRACKING ALGORITHM USING N-QUEENS PROBLEM { 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)
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; else state = 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 Primality 101 is prime 103 is prime 107 is prime 109 is prime 113 is prime 127 is prime 131 is prime 137 is prime 139 is prime 149 is prime 151 is prime 157 is prime 163 is prime 167 is prime 173 is prime 179 is prime 181 is prime 191 is prime 193 is prime 197 is prime 199 is prime RESULT: Thus the java program for Randomized algorithm using Primality Testing has been executed and output was verified successfully.
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();
EX.NO:6a IMPLEMENTATION OF CONCURRENT QUEUE USING PRODUCER-CONSUMER PROBLEM
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.java C:\Users\admin\Desktop>java ConsumerProducer Producer: put...1 Consumer: got...1 Producer: put...2 Consumer: got...2 Producer: put...3 Consumer: got...3 Producer: put...4 Consumer: got...4 Producer: put...5 Consumer: got...5 Producer: put...6 Consumer: got...6 Producer: put...7 Consumer: got...7 Producer: put...8 Consumer: got...8 Producer: put...9 Consumer: got...9 Producer: put...10 Consumer: got...10 RESULT : Thus, the java program for Producer-Consumer problem has been implemented and output was verified successfully.
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; }
IMPLEMENTATION OF CONCURRENT STACKS USING VARIOUS LOCKING AND SYNCHRONIZATION MECHANISMS
}
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: null Popped: null Popped: null Pushed: true Popped: 2008 Pushed: true Popped: 2008 Pushed: true Popped: 2008 RESULT : Thus, the java program for various locking and synchronization mechanisms has been implemented and output was verified successfully.
AIM:
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() {
EX.NO: 7 DEVELOP A SIMPLE APPLICATIONS INVOLVING CONCURRENCY
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 SyncTest1 MyProcess ID : 1 MyProcess ID : 2 MyProcess ID : 3 MyProcess ID : 4 [1, 1, 5] MyProcess ID : 1 MyProcess ID : 1 MyProcess ID : 3 [1] MyProcess ID : 2 MyProcess ID : 4 MyProcess ID : 4 MyProcess ID : 1 MyProcess ID : 3 Waiting or new numbers to be pushed MyProcess ID : 2 [] MyProcess ID : 4 MyProcess ID : 4 MyProcess ID : 3 MyProcess ID : 2 [] MyProcess ID : 1 Waiting or new numbers to be pushed MyProcess ID : 4 MyProcess ID : 2 Waiting or new numbers to be pushed MyProcess ID : 3 MyProcess ID : 4 Waiting or new numbers to be pushed MyProcess ID : 1 [] MyProcess ID : 4 MyProcess ID : 1 [] MyProcess ID : 2 MyProcess ID : 3 [] MyProcess ID : 3 [] MyProcess ID : 1 [] MyProcess ID : 3 [] MyProcess ID : 1 Waiting or new numbers to be pushed MyProcess ID : 4 Waiting or new numbers to be pushed MyProcess ID : 2 [] MyProcess ID : 1 [] MyProcess ID : 3 MyProcess ID : 1 MyProcess ID : 2 Waiting or new numbers to be pushed MyProcess ID : 4 MyProcess ID : 2 [] MyProcess ID : 3 Waiting or new numbers to be pushed MyProcess ID : 3 MyProcess ID : 2 Waiting or new numbers to be pushed MyProcess ID : 1 MyProcess ID : 4 [] MyProcess ID : 2 MyProcess ID : 4 [] MyProcess ID : 4 [] MyProcess ID : 4 [] MyProcess ID : 4 [] MyProcess ID : 4 Waiting or new numbers to be pushed MyProcess ID : 4 [] MyProcess ID : 3 Waiting or new numbers to be pushed MyProcess ID : 4 [] MyProcess ID : 4 Waiting or new numbers to be pushed MyProcess ID : 4 [] MyProcess ID : 3 MyProcess ID : 1 [9] MyProcess ID : 2 MyProcess ID : 3 MyProcess ID : 2 MyProcess ID : 4 [] MyProcess ID : 1 [] MyProcess ID : 4 [] MyProcess ID : 4 Waiting or new numbers to be pushed MyProcess ID : 4 Waiting or new numbers to be pushed MyProcess ID : 3 [] MyProcess ID : 1 MyProcess ID : 4 Waiting or new numbers to be pushed MyProcess ID : 1 [] MyProcess ID : 2 MyProcess ID : 3 MyProcess ID : 2 MyProcess ID : 4 MyProcess ID : 3 MyProcess ID : 1 [] MyProcess ID : 1 Waiting or new numbers to be pushed MyProcess ID : 2 MyProcess ID : 1 Waiting or new numbers to be pushed MyProcess ID : 4 [] MyProcess ID : 1 MyProcess 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.