Give Java solution to Bounded buffer problem.
import java.io.*;class Buffer {
private final int MaxBuffSize;
private char[] store;
private int BufferStart, BufferEnd, BufferSize;
public Buffer(int size) {
MaxBuffSize = size;
BufferEnd = -1;
BufferStart = 0;
BufferSize = 0;
store = new char[MaxBuffSize];
}
public synchronized void insert(char ch) {
try {
while (BufferSize == MaxBuffSize) {
wait();
}
BufferEnd = (BufferEnd + 1) % MaxBuffSize;
store[BufferEnd] = ch;
BufferSize++;
notifyAll();
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}
public synchronized char delete()
{
try
{
while (BufferSize == 0)
{
wait();
}
char ch = store[BufferStart];
BufferStart = (BufferStart + 1) % MaxBuffSize;
BufferSize--;
notifyAll();
return ch;
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
return 'i';
}
}
}
class Consumer extends Thread
{
private final Buffer buffer;
public Consumer(Buffer b)
{
buffer = b;
}
public void run() {
while (!Thread.currentThread().isInterrupted())
{
char c = buffer.delete();
System.out.print(c);
}
}
}
class Producer extends Thread
{
private final Buffer buffer;
private InputStreamReader in = new InputStreamReader(System.in);
public Producer(Buffer b)
{
buffer = b;
}
public void run()
{
try
{
while (!Thread.currentThread().isInterrupted())
{
int c = in.read();
if (c == -1) break; // -1 is eof
buffer.insert((char)c);
}
}
catch (IOException e) {}
}
}
class BoundedBuffer
{
public static void main(String[] args)
{
System.out.println("program starting");
Buffer buffer = new Buffer(5); // buffer has size 5
Producer prod = new Producer(buffer);
Consumer cons = new Consumer(buffer);
prod.start();
cons.start();
try
{
prod.join();
cons.interrupt();
}
catch (InterruptedException e) {}
System.out.println("End of Program");
}}
GENERATING PRIME AND FIBONACCI NUMBERS USING MULTITHREADING
import java.io.*;
import java.util.*;
class MyThread1 extends Thread
{
private PipedReader pr;
private PipedWriter pw;
MyThread1(PipedReader pr, pipedWriter pw)
{
this.pr = pr;
this.pw = pw;
}
public void run()
{
try
{
int I;
for (i=1;i<10;i++)
{
int j;
for (j=2; j<i; j++)
{
int n = i%j;
if (n==0)
{
break;
}
}
if(I ==j)
{
pw.write(i+\n);
}
}
pw.close();
}
catch (IOException e)
{
}
}
}
class MyThread2 extends Thread
{
private PipedReader pr;
Private PipedWriter pw;
MyThread2(PipedReader pr, PipedWriter pw)
{
this.pr;
this.pw=pw;
}
public void run()
{
try
{
int f1,f2=1,f3=1;
for(int i=1;i<10;i++)
{
pw.write(f3+\n);
f1=f2;
f2=f3;
f3=f1+f2;
}
catch (IOException e)
{
}
}
}
class MultithreadedProgram
{
public static void main(string[] args)throws Exception
{
ArrayList list1=new ArrayList list();
ArrayList list list2=new ArrayList list();
PipedWriter pw1=new PipedWriter();
PipedReader pr1=new PipedReader(pw1);
MyThread1 mt1=new MyThread1(pr1,pw1);
System.out.println(Prime Numbers);
mt1.start();
int item1;
while((item1=pr1.read())!=-1)
{
char ch1=((char)item1);
System.out.print(Character.toString(ch1));
list1.add(Character.toString(ch1));
}
pr1.close();
PipedWriter pw2=new pipedWriter();
PipedReader pr2=new PipedReader(pw2);
MyThread2 mt2=new MyThread2(pr2,pw2);
System.out.println(Fibonacci Series);
mt2.satrt();
int item2;
while ((item2=pr2.read())!=-1)
{
char ch2=((char)item2);
System.out.print(Character.toString(ch2));
list2.add(Character.toString(ch2));
}
pr2.close();
System.out.println(Elements common to both lists are:);
list1.retainAll(list2);
for(int i=0;i<list1.size();i++)
{
System.out.print(list1.get(i));
}
}
}
Implement FCFS scheduling in Java.
import java.util.Scanner;
class Process{
int wait;
int submission;
int bursts;
int turnAround;
int completionTime = 0;
Process(int sub,int bur){
submission = sub;
bursts = bur;
}
}
class Processmain{
public static void main(String[] args){
int wait = 0,x=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of processes:");
int n = s.nextInt();
Process[] myProcess = new Process[n];
for(int i=0;i<n;i++){
System.out.println("Enter Arrival time and bursts: ");
int sub = s.nextInt();
int bur = s.nextInt();
myProcess[i] = new Process(sub,bur);
}
for(int i=0;i<myProcess.length;i++){
x = x+myProcess[i].bursts;
myProcess[i].completionTime = x;
myProcess[i].turnAround = myProcess[i].completionTime - myProcess[i].submission;
myProcess[i].wait = myProcess[i].turnAround - myProcess[i].bursts;
System.out.println("Process "+i+":");
System.out.println("Turnaround\tCompletion\twaiting");
System.out.println(myProcess[i].turnAround+"\t\t\t"+myProcess[i].completionTime+"\t\t\t"+myProcess[i].wait);
}
}
}
Write a Java program that implements the bankers algorithm
import java.io.*;
class Banker
{
int avail[ ];
int max[ ][ ] = { {3,2,2,1}, {8,12,0,0}, {2,1,0,0}, {4,3,0,0}, {2,0,3,1}};
int alloc[ ][ ] = { {1,1,1,0}, {2,1,0,0}, {1,0,0,0}, {2,1,0,0}, {1,0,0,0}};
int need[ ][ ];
int m,n;
Banker()
{
m = 4;
n = 5;
avail = new int[4];
avail[0] = 16; // Number of Registers
avail[1] = 50; // Number of Files
avail[2] = 5; // Number of Ports
avail[3] = 2; // Number of Printer
need = new int[5][4];
for(int i=0;i<5; i++)
for(int j=0;j<4; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
boolean isSafe()
{
int work[] = new int[m];
boolean finish[] = new boolean[n];
for(int i=0 ;i<m; i++)
work[i] = avail[i];
for(int i=0 ;i<n; i++)
finish[i] = false;
for(int i=0; i<n; i++)
{
if(finish[i]==false)
{
boolean incomplete=false;
for(int j=0;j<m; j++)
{
if(need[i][j]>work[j])
{
incomplete = true;
//System.out.println(i + ":" + j + ":" + need[i][j] + ":" + work[j]);
}
if(need[i][j]!=0 && need[i][j]<=work[j])
{
work[j] = work[j] - need[i][j];
}
}
if(!incomplete)
{
finish[i]=true;
}
if(finish[i])
System.out.println("Process " + i + " can be completed");
else
System.out.println("Process " + i + " can't be completed");
}
}
for(int i=0; i<n; i++)
{
if(!finish[i])
{
return false;
}
}
return true;
}
void resourceRequest()
{
int request[][] = { {1,1,1,0}, {2,2,0,0}, {1,1,0,1}, {1,1,0,0}, {1,0,0,0}};
boolean safe=true;
for(int i=0; i<n; i++)
{
for(int j=0;j<m; j++)
{
if(request[i][j]<=need[i][j])
{
if(request[i][j]<=avail[j])
{
avail[j] = avail[j] - request[i][j];
alloc[i][j] = alloc[i][j] + request[i][j];
need[i][j] = need[i][j] - request[i][j];
}
else
{
System.out.println("Hey process " + i + "! resource " + j + " is not available now...try again later...");
}
}
else
{
System.out.println("Process " + i + " has exceeded request for resource " + j + " hence is unsafe");
safe = false;
}
}
}
if(safe)
{
System.out.println("the system is safe...");
}
else
{
System.out.println("the system is unsafe...");
}
}
}
class os
{
public static void main(String args[]) throws Exception
{
Banker b = new Banker();
System.out.println("Applying safety algorithm...");
if(b.isSafe())
{
System.out.println("The system is in safe state...");
}
else
{
System.out.println("The system is not in safe state....");
}
System.out.println("Applying resource request algo...");
b.resourceRequest();
}
}
Write a Java program that implements the FIFO page-replacement algorithm
import java.io.*;
class MemMgmt
{
String frame_sequence;
int mem_block[];
MemMgmt(String fs,int n)
{
frame_sequence = fs;
mem_block = new int[n];
for(int i=0;i<n; i++)
mem_block[i]=-1;
}
void dispMemBlock()
{
System.out.print("|");
for(int i=0;i<mem_block.length;i++)
{
System.out.print(mem_block[i]+"|");
}
System.out.println();
}
void fcfs()
{
System.out.println("======= FIFO ===========");
String strpages[] = frame_sequence.split(" ");
int pages[] = new int[strpages.length];
for(int i=0; i<strpages.length; i++)
pages[i] = Integer.parseInt(strpages[i]);
int mem_block_num=0, page_faults=0;
System.out.println("Initial Memory layout...");
dispMemBlock();
for(int i=0; i<pages.length; i++)
{
boolean present=false;
for(int j=0;j<mem_block.length;j++)
{
if(mem_block[j] == pages[i])
{
present=true;
break;
}
}
if(!present)
{
mem_block[mem_block_num] = pages[i];
mem_block_num++;
page_faults++;
}
if(mem_block_num==mem_block.length)
mem_block_num=0;
System.out.println("Loading page no." + (i+1) + ":" + pages[i]);
dispMemBlock();
}
System.out.println("Total Number of page faults:" + page_faults);
}
}
class os7
{
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter page frame sequence(separated by space):");
String frame_sequence = "7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1";
MemMgmt m = new MemMgmt(frame_sequence,3);
m.fcfs();
}
}
Write a Java program to implements synchronized access to shared resources
class room
{
synchronized void takeslecture(String name)throws InterruptedException
{
System.out.println(name+"Enters...");
Thread.sleep(250);
System.out.println(name+"starts lecture...");
Thread.sleep(500);
System.out.println(name+"Exits");
Thread.sleep(250);
}
}
class lecture implements Runnable
{
String name;
room r;
Thread t;
lecture(String n,room r)
{
name=n;
t=new Thread(this,n);
this.r=r;
}
public void start()
{
t.start();
}
public void run()
{
try
{
r.takeslecture(name);
}
catch(InterruptedException iae)
{
System.out.println(name+"opration interrupted...");
}
}
}
class os2
{
public static void main(String args[])
{
room r=new room();
lecture kamlakar=new lecture("kamlakar sir",r);
lecture madhavi=new lecture("madhaci maam",r);
lecture prajisha=new lecture("prajisha maam",r);
kamlakar.start();
madhavi.start();
prajisha.start();
}
}
Design a File System in Java.
* Program to input text in a file
import java.io.*;import java.util.Scanner;
public class WriteFile
{
public static void main(String args[])
{
String FileName;
Scanner sc=new Scanner(System.in);
System.out.println("Enter name of the You want to write");
FileName=sc.nextLine();
try
{
File f1=new File(FileName);
if(f1.exists()==false)
{
if (f1.createNewFile())
{
System.out.println("file created succesfully");
}
else
{
System.out.println("file created failed");
System.exit(0);
}
}
String text;
FileOutputStream fileout=new FileOutputStream(f1);
int ch;
while(true)
{
System.out.println("enter text to write into file and enter 0 to stop wrinting ");
text=sc.nextLine();
if (text.equals("0"))
break;
else
{
fileout.write(text.getBytes());
fileout.flush();
}
//System.out.println("do you want to write one more (1/0)?");
//ch=sc.nextInt();
}
fileout.close();
System.out.println("file saved");
}
catch (Exception ex)
{
System.out.println("exception"+ex.toString());
}
}
}
* Program to read text from a file
import java.io.*;
import java.util.Scanner;
public class ReadFile
{
public static void main(String args[])
{
String FileName;
Scanner sc=new Scanner(System.in);
System.out.println("Enter name of the You want to read");
FileName=sc.nextLine();
try
{
File f1=new File(FileName);
if(f1.exists()==false)
{
System.out.println("file does not not exits");
System.exit(0);
}
String text;
int val;
FileInputStream fileIn=new FileInputStream(f1);
System.out.println("content of file is:");
while((val=fileIn.read())!=-1)
{
System.out.print((char)val);
}
System.out.println();
fileIn.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Demonstrate OPTIMAL PAGE REPLACEMENT algorithm
import java.io.*;
class MemMgmt
{
String frame_sequence;
int mem_block[];
MemMgmt(String fs,int n)
{
frame_sequence = fs;
mem_block = new int[n];
for(int i=0;i<n; i++)
mem_block[i]=-1;
}
void dispMemBlock()
{
System.out.print("|");
for(int i=0;i<mem_block.length;i++)
{
System.out.print(mem_block[i]+"|");
}
System.out.println();
}
void oppr()
{
System.out.println("======= Optimal Page Replacement ===========");
String strpages[] = frame_sequence.split(" ");
int pages[] = new int[strpages.length];
int i=0;
for(i=0; i<strpages.length; i++)
pages[i] = Integer.parseInt(strpages[i]);
int mem_block_num=0,page_faults=0;
System.out.println("Initial Memory layout...");
dispMemBlock();
for(i=0; i<mem_block.length; i++)
{
boolean present=false;
for(int j=0;j<mem_block.length;j++)
{
if(mem_block[j] == pages[i])
{
present=true;
break;
}
}
if(!present)
{
mem_block[mem_block_num] = pages[i];
mem_block_num++;
page_faults++;
}
System.out.println("Loading page no." + (i+1) + ":" + pages[i]);
dispMemBlock();
}
for(; i<pages.length; i++)
{
boolean present=false;
for(int j=0;j<mem_block.length;j++)
{
if(mem_block[j] == pages[i])
{
present=true;
break;
}
}
if(!present)
{
mem_block_num=-1;
int longest_page=-1;
for(int j=0;j<mem_block.length; j++)
{
int k=0;
for(k=i+1; k<pages.length; k++)
{
if(mem_block[j] == pages[k])
{
if(k>longest_page)
{
longest_page = k;
mem_block_num = j;
}
break;
}
}
if(k==pages.length)
{
longest_page = pages.length;
mem_block_num = j;
}
}
mem_block[mem_block_num] = pages[i];
page_faults++;
}
System.out.println("Loading page no." + (i+1) + ":" + pages[i]);
dispMemBlock();
}
System.out.println("Total Number of page faults:" + page_faults);
}
}
class os8
{
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter page frame sequence(separated by space):");
//String frame_sequence = br.readLine();
String frame_sequence = "7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1";
//System.out.println("Enter page replacement algo:");
//int i = Integer.parseInt(br.readLine());
MemMgmt m = new MemMgmt(frame_sequence,3);
//if(i==1)
//m.fcfs();
//else
//if(i==2)
m.oppr();
}
}
//RR schedulingm algorith
import java.io.*;class job implements Runnable
{
int process_id, no_of_instr, time_quantum;
Thread t;
job(int pid,int instr,int tq)
{
process_id=pid;
no_of_instr=instr;
time_quantum=tq;
t=new Thread(this);
t.start();
}
public void run()
{
try
{
for(int i=1;i<=no_of_instr;i++)
{
System.out.println("Executing instr no. "+i+" of process"+process_id);
Thread.sleep(time_quantum);
}
System.out.println("join"+process_id+" is over");
}
catch(InterruptedException e)
{
System.out.println("The job has been inturrepted...");
}
}
}
class os1
{
public static void main(String args[])
{
try
{
int process_id=100,time_quantum=100;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a process user starting number:");
process_id=Integer.parseInt(br.readLine());
System.out.println("Enter a time_quantum(in mills):");
time_quantum=Integer.parseInt(br.readLine());
job j1=new job(++process_id,10,time_quantum);
job j2=new job(++process_id,6,time_quantum);
job j3=new job(++process_id,8,time_quantum);
}
catch(Exception e)
{
System.out.println("Some process failed to complete...");
System.out.println("Please contact system admin...");
}
}
}
//producer consumer problem
class Q{int n;
boolean valueset=false;
synchronized int get(){
while (!valueset)
try{
wait();
}catch(InterruptedException e){
System.out.println("InterruptedException caught");
}
System.out.println("Got:"+n);
valueset=false;
notify();
return n;
}
synchronized void put(int n){
while(valueset)
try{
wait();
}catch(InterruptedException e){
System.out.println("InterruptedException caught");
}
this.n=n;
valueset=true;
System.out.println("Put:"+n);
notify();
}
}
class Producer implements Runnable{
Q q;
Producer(Q q){
this.q=q;
new Thread(this,"Producer").start();
}
public void run(){
int i=0;
while(true){
q.put(i++);
}
}
}
class Consumer implements Runnable{
Q q;
Consumer(Q q){
this.q=q;
new Thread(this,"Consumer").start();
}
public void run(){
while(true){
q.get();
}
}
}
class PCFixed{
public static void main(String args[])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("press ctrl+c to stop");
}
}
//Give solution to the producer consumer problem using message passing
class Item{volatile int content;
public synchronized void setContent(int content)
{
this.content=content;
}
public synchronized int getContent()
{
return content;
}
}
class Producer implements Runnable{
Item item;
Producer(Item item)
{
this.item=item;
}
public Item getItem(){
return item;
}
public void setItem(Item item){
this.item=item;
}
public void run(){
int i=0;
synchronized(this)
{
while(true)
{
++i;
if (i==10) return;
System.out.println("Putting the value in item"+i);
item.setContent(i);
notify();
try{
wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
class Consumer implements Runnable{
Producer producer;
Consumer(Producer producer){
this.producer=producer;
}
public void run()
{
synchronized(producer)
{
while(true){
System.out.println("Consuming"+producer.getItem().getContent());
producer.notify();
try{
if(producer.getItem().getContent()==9)
return;
producer.wait();
}catch(InterruptedException e)
{
//to do auto - generated catch block
e.printStackTrace();
}
}
}
}
}
public class Execute{
public static void main(String args[]){
Item item1=new Item();
Producer producer=new Producer(item1);
Consumer consumer=new Consumer(producer);
Thread producerThread=new Thread(producer);
Thread consumerThread=new Thread(consumer);
producerThread.start();
consumerThread.start();
}
}
Give solution to the readerswriters problem using Java synchronization
* Database File/** This class represents a database. There are many competing threads wishing to read and write. It is acceptable to have multiple processes reading at the same time, but if one thread is writing then no other process may either read or write. */
public class Database{
private int readers; // number of active readers
/**
Initializes this database.
*/
public Database()
{
this.readers = 0;
}
/**
Read from this database.
@param number Number of the reader.
*/
public void read(int number)
{
synchronized(this)
{
this.readers++;
System.out.println("Reader " + number + " starts reading.");
}
final int DELAY = 5000;
try
{
Thread.sleep((int) (Math.random() * DELAY));
}
catch (InterruptedException e) {}
synchronized(this)
{
System.out.println("Reader " + number + " stops reading.");
this.readers--;
if (this.readers == 0)
{
this.notifyAll();
}
}
}
/**
Writes to this database.
@param number Number of the writer.
*/
public synchronized void write(int number)
{
while (this.readers != 0)
{
try
{
this.wait();
}
catch (InterruptedException e) {}
}
System.out.println("Writer " + number + " starts writing.");
final int DELAY = 5000;
try
{
Thread.sleep((int) (Math.random() * DELAY));
}
catch (InterruptedException e) {}
System.out.println("Writer " + number + " stops writing.");
this.notifyAll();
}
}
* Readers File/** This class represents a reader.*/
public class Reader extends Thread{
private static int readers = 0; // number of readers
private int number;
private Database database;
/**
Creates a Reader for the specified database.
@param database database from which to be read.
*/
public Reader(Database database)
{
this.database = database;
this.number = Reader.readers++;
}
/**
Reads.
*/
public void run()
{
while (true)
{
final int DELAY = 5000;
try
{
Thread.sleep((int) (Math.random() * DELAY));
}
catch (InterruptedException e) {}
this.database.read(this.number);
}}}
* Writers File/** This class represents a writer.*/
public class Writer extends Thread{
private static int writers = 0; // number of writers
private int number;
private Database database;
/**
Creates a Writer for the specified database.
@param database database to which to write.
*/
public Writer(Database database)
{
this.database = database;
this.number = Writer.writers++;
}
/**
Writes.
*/
public void run()
{
while (true)
{
final int DELAY = 5000;
try
{
Thread.sleep((int) (Math.random() * DELAY));
}
catch (InterruptedException e) {}
this.database.write(this.number);
}}}
* Simulator File/**
This app creates a specified number of readers andwriters and starts them.
*/
public class Simulator
{
/**
Creates the specified number of readers and writers and starts them.
@param args[0] The number of readers.
@param args[1] The number of writers.
*/
public static void main(String[] args)
{
if (args.length < 2)
{
System.out.println("Usage: java Simulator <number of readers> <number of writers>");
}
else
{
final int READERS = Integer.parseInt(args[0]);
final int WRITERS = Integer.parseInt(args[1]);
Database database = new Database();
for (int i = 0; i < READERS; i++)
{
new Reader(database).start();
}
for (int i = 0; i < WRITERS; i++)
{
new Writer(database).start();
}
}
}
}
Comments
Post a Comment