Hey guys. I was told to do an assignment, to demonstrate how a high priority thread gives a low priority thread a chance to run using the sleep function. The assignment has already been submitted and already graded. The following code when compiled not only creates a ThreadSleep.class file, but also creates a LowPriorityThread.class and a HighPriorityThread.class file.
The questions i pose:
why the compilation of external LowPriorityThread and external HighPriorityThread?
What is the role of the external HighPriorityThread.class and external LowPriorityThread.class?
Are these external class files necessary?
I would appreciate some comments on this.
//Importing libraries
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//Declarations
public class ThreadSleep extends JFrame {
private HighPriorityThread high;
private LowPriorityThread low;
private JTextArea output;
//Initializing
public ThreadSleep()
{
super( "ThreadSleep" );
output = new JTextArea( 10, 20 );
getContentPane().add( output );
setSize( 200, 250 );
setVisible( true );
//Starting the threads
high = new HighPriorityThread( output );
high.start();
low = new LowPriorityThread( output );
low.start();
}
//Main function
public static void main( String args[] )
{
ThreadSleep app = new ThreadSleep();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}
//Creating HighPriorityThread subclass
class HighPriorityThread extends Thread {
private JTextArea display;
public HighPriorityThread( JTextArea a )
{
display = a;
setPriority( Thread.MAX_PRIORITY );
}
//Implementing "sleep"
public void run()
{
for ( int x = 1; x <= 5; x++ ) {
try {
sleep( ( int ) ( Math.random() * 200 ) );
}
catch ( Exception e ) {
JOptionPane.showMessageDialog(
null, e.toString(), "Exception",
JOptionPane.ERROR_MESSAGE );
}
display.append( "This is a High Priority Thread!\n" );
}
}
}
//Creating LowPriorityThread subclass
class LowPriorityThread extends Thread {
private JTextArea display;
public LowPriorityThread( JTextArea a )
{
display = a;
setPriority( Thread.MIN_PRIORITY );
}
public void run()
{
for ( int y = 1; y <= 5; y++ )
display.append( "This is a Low Priority Thread!!!\n" );
}
} //End of ThreadSleep program