-- Feb 20 In-Class Exercise Thread
import java.lang.Thread;
public class SumDemo extends Thread
{
public SumDemo(SumDemo spawner, int low, int high)
{
this.high = high;
this.low = low;
this.spawner = spawner;
done = false;
c = 0;
}
public void run()
{
SumDemo firstHalf = null;
SumDemo secondHalf = null;
done = false;
if(low == high)
{
c = a[low];
}
else
{
int mid = (low + high) / 2;
firstHalf = new SumDemo(this, low, mid);
firstHalf.start();
secondHalf = new SumDemo(this, mid + 1, high);
secondHalf.start();
}
if(low != high ){
firstHalf.sync();
secondHalf.sync();
c = firstHalf.c<secondHalf.c?firstHalf.c:secondHalf.c;
}
done = true;
if(spawner == null)
{
System.out.println(c);
}
}
public synchronized void sync()
{
if(!done)
{
try
{
wait();
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
}
public static void main(String args[])
{
SumDemo parent = new SumDemo(null, 0, a.length - 1);
parent.start();
}
int low;
int high;
int c = 0;
SumDemo spawner;
boolean done;
static int a[] = {4, 3, 9, -1, 11};
}
(
Edited: 2019-02-20)
import java.lang.Thread;
public class SumDemo extends Thread
{
public SumDemo(SumDemo spawner, int low, int high)
{
this.high = high;
this.low = low;
this.spawner = spawner;
done = false;
c = 0;
}
public void run()
{
SumDemo firstHalf = null;
SumDemo secondHalf = null;
done = false;
if(low == high)
{
c = a[low];
}
else
{
int mid = (low + high) / 2;
firstHalf = new SumDemo(this, low, mid);
firstHalf.start();
secondHalf = new SumDemo(this, mid + 1, high);
secondHalf.start();
}
if(low != high ){
firstHalf.sync();
secondHalf.sync();
'''c = firstHalf.c<secondHalf.c?firstHalf.c:secondHalf.c;'''
}
done = true;
if(spawner == null)
{
System.out.println(c);
}
}
public synchronized void sync()
{
if(!done)
{
try
{
wait();
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
}
public static void main(String args[])
{
SumDemo parent = new SumDemo(null, 0, a.length - 1);
parent.start();
}
int low;
int high;
int c = 0;
SumDemo spawner;
boolean done;
static int a[] = {4, 3, 9, -1, 11};
}