Master.java
public class Master
{
private Resource resource;
private int sk=2;
private Resource res=new Resource();
private Slave[] slave=new Slave[sk];
public Resource getResource() {
return resource;
}
public void setResource(Resource theResource) {
resource = theResource;
}
public void slave()
{
}
public void run()
{
for(int i=0;i<sk;i++)
slave[i]=new Slave(res);
for(int i=0;i<sk;i++)
slave[i].start();
for(int i=0;i<sk;i++)
{
try
{
slave[i].join();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
System.out.println(slave[i].getName()+"--has died");
}
}
System.out.println("Master Exiting now");
}
public void start() {
}
}
Slave.java
public class Slave extends Thread
{
private Resource resource;
private Resource sharedResource;
private Boolean done=false;
public void halt()
{
done=true;
}
public Slave(Resource res)
{
sharedResource=res;
}
protected boolean task()
{
int status=sharedResource.innerStatus();
return(status>7);
}
public Resource getResource()
{
return resource;
}
public void setResource(Resource theResource)
{
resource = theResource;
}
public void run()
{
while(done!=true)
{
done=task();
try
{
Thread.sleep(500);
}
catch(Exception e)
{
}
}
}
}
Resource.java
public class Resource
{
private TestMaster testmaster;
private int status=0;
public synchronized int innerStatus()
{
int local=status;
System.out.println("Ststus="+local);
local++;
try
{
Thread.sleep(500);
}
catch(Exception e)
{
}
status=local;
System.out.println("New Status="+local);
return status;
}
public TestMaster getTestmaster()
{
return testmaster;
}
public void setTestmaster(TestMaster theTestmaster)
{
testmaster = theTestmaster;
}
private Master master;
public Master getMaster()
{
return master;
}
public void setMaster(Master theMaster)
{
master = theMaster;
}
private Slave slave;
public Slave getSlave()
{
return slave;
}
}
TestMaster.java
public class TestMaster
{
private Resource resource;
public Resource getResource()
{
return resource;
}
public void setResource(Resource theResource)
{
resource = theResource;
}
public static void main(String args[])
{
Master ms=new Master();
ms.run();
}
}
No comments:
Post a Comment