I'm currently in an operating systems class at University of Houston. I will absolutely admit that this is a Lab for our class, but I am -not- looking for ANYONE to do my homework.
The code of the lab is as follows:
import java.lang.*;
import java.io.*;
import java.util.*;
public class Counter{
private int count1 = 0, count2 = 0;
private int max_count = 100000;
private int number_of_threads = 10;
private int threads_quit;
public Counter()
{
threads_quit = 0;
startThreads();
}
public synchronized int getNextNumber1()
{
int temp;
if(count1 < max_count)
{ temp = count1;
count1 = count1 + 1;
return(temp);
}
else return(-1);
}
public synchronized int getNextNumber2()
{
int temp;
if(count2 < max_count)
{ temp = count2;
count2 = count2 + 1;
return(temp);
}
else return(-1);
}
public synchronized int threads_quit_increase()
{
threads_quit = threads_quit + 1;
if (threads_quit < number_of_threads) return (0);
else return (-1);
}
public void startThreads()
{
int i = 0;
for(i = 0; i < number_of_threads; i++)
{
CounterThread ct = new CounterThread(this, i);
ct.start();
}
}
public static void main(String args[])
{
Counter a = new Counter();
}
class CounterThread extends Thread
{
Counter parent;
int number;
public CounterThread(Counter parent, int number)
{
this.parent = parent;
this.number = number;
}
public void run()
{
int n1=parent.getNextNumber1(), n2=parent.getNextNumber2();
while (n1 != -1 && n2 != -1 && n1 == n2)
{
n1=parent.getNextNumber1();
n2=parent.getNextNumber2();
}
if (n1 != n2)
System.out.println("Two counters are discrepant!");
System.out.println("Thread ID " + number + " is quitting!");
if (threads_quit_increase() == -1)
System.out.println("All threads have quitted. Done!");
}
}
}
Our assignment is to modify the code in such a way where the 2 threads are never discrepant. While the code works with a max_count of 1000, as soon as you increase the max_count one of the threads always runs away from the other.
This is a lesson in Synchronization, if someone would be willing to explain how it works in this program I would be extremely grateful. I've read up on it but when I try to apply it to this Lab I get lost.
Thank you in advance.

New Topic/Question
Reply



MultiQuote






|