Tuesday 3 January 2012

Thread Race in JAVA

1. Start Command Line on Windows.
  • Open cmd(Windows) or terminal(Unix)
  • Set Environment Variable JDK_HOME and JRE_HOME on Windows with jdk bin directory(eg. C:\Program Files\Java\jdk1.6.24\bin).
  • Set path to add these to two variables 
            eg. cmd> set path="%path%";%JDK_HOME%;%JRE_HOME
                  cmd>path
  • check javac and java commands in the command Line.
  • Try the following two commands in cmd.   
            cmd>javac -version
            cmd>java -version
  • If the versions are different the reconfigure your paths      

2.Type the following command in command line(Windows).
   
            cmd>copy con RaceCourse.java

3.Copy the following code and Paste into cmd. Press Ctrl+Z and your File gets        Saved.


import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;

//THE RACE COURSE TO RUN ON

public class RaceCourse extends JPanel implements Runnable {

    private static final long serialVersionUID = 1L;
    
   int threadLength1, threadLength2, threadLength3;
    private static final int START_X = 50;
    
private static final int START_Y = 50;

    private static final int INC = 1;

    private static final int THREAD_WIDTH = 30;

    private static final int THREAD_SEPERATION = 90;

    boolean thread1 = false, thread2 = false;

    public RaceCourse() {

       

        threadLength1 = threadLength2 = threadLength3 = INC;

        setSize(getPreferredSize());

        RaceCourse.this.setBackground(Color.white);

    }

    public Dimension getPreferredSize() {

        return new Dimension(600, 400);

    }

    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g;

         if (thread1) {

            g2d.setColor(new Color(200, 20, 20, 255));

            g2d.fillRect(START_X, START_Y, threadLength1, THREAD_WIDTH);

        }

        else if (thread2) {

            g2d.setColor(new Color(20, 200, 20, 255));

            g2d.fillRect(START_X, START_Y + THREAD_SEPERATION, threadLength2, THREAD_WIDTH);

        } else {

            g2d.setColor(new Color(20, 20, 200, 255));

            g2d.fillRect(START_X, START_Y + 2 * THREAD_SEPERATION, threadLength3, THREAD_WIDTH);

        }

    }

    // A comman run method shared by three Threads.

    public void run() {

        while (true)

            try {

                Thread.sleep(100);

                System.out.println("Current Thread:"
                        + Thread.currentThread().getName());

                if (Thread.currentThread().getName().equals("thread1")) {

                    thread1 = true;

                    thread2 = false;

                    threadLength1 = threadLength1 + INC;

                    repaint(START_X, START_Y, threadLength1, THREAD_WIDTH);

                    // this.wait();

                } else if (Thread.currentThread().getName().equals("thread2")) {

                    Thread.sleep(100);

                    // Thread.yield();

                    thread2 = true;

                    thread1 = false;

                    threadLength2 = threadLength2 + INC;

                    repaint(START_X, START_Y + THREAD_SEPERATION, threadLength2, THREAD_WIDTH);

                    // this.notify();

                } else {

                    Thread.sleep(400);

                    thread2 = false;

                    thread1 = false;

                    threadLength3 = threadLength3 + INC;

                    repaint(START_X, START_Y + 2 * THREAD_SEPERATION, threadLength3, THREAD_WIDTH);

                    // this.wait();

                }

            }

            catch (IllegalMonitorStateException is) {

                System.err.println("Error:" + is);

            } catch (InterruptedException ie) {

                System.err.println("Error:" + ie);

            }

    }

}



 4.Compile the above Code
      javac -d classes RaceCourse.java
  • Above command compiles the java file and stores into classes folder if it exists(create classes folder next to RaceCourse.java file if it doesn't exist)
  • If it compiles successfully without any errors go to next step.
 5.Create a new File ThreadRace.java and paste the following code same as          step 3        

            cmd>copy con ThreadRace.java
                     [paste your your code here]
                [Press Ctrl+Z]


import javax.swing.JFrame;
import javax.swing.JScrollPane;

public class ThreadRace extends JFrame {

    private static final long serialVersionUID = 1L;
    RaceCourse canvas;

    public ThreadRace() {

        super(" Race Course ");

        canvas = new RaceCourse();

        setSize(300, 300);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        getContentPane().add(new JScrollPane(canvas));

        setVisible(true);
        pack();
    }

    public static void main(String[] args) {

        ThreadRace course = new ThreadRace();

        Thread thread1 = new Thread(course.canvas, "thread1");

        Thread thread2 = new Thread(course.canvas, "thread2");
        Thread thread3 = new Thread(course.canvas, "thread3");

        thread1.setPriority(Thread.MAX_PRIORITY);
        thread2.setPriority(Thread.NORM_PRIORITY);
        thread3.setPriority(Thread.MIN_PRIORITY);

        thread1.start();
        thread2.start();
        thread3.start();

    }

}
6.Compile ThreadRace.java as shown in step 4

  •  Check if ThreadRace.class and RaceCourse.class file is located in classes folder
7.Run ThreadRace.class from command prompt
     
            cmd>java -classpath classes ThreadRace