Results 1 to 11 of 11
  1. #1
    AlQassabi is offline Member
    Join Date
    Feb 2011
    Posts
    6
    Rep Power
    0

    Default Problem running many Threads !!

    hi, im programming a simple mathematical kids game using Threads
    the program should draw an equation in a frame then display it for about 3 sec
    i did all that; BUT the problem is when i run more than one thread all the threads are drawn in the frame,
    i have the code for the thread class and main class



    Main Class Code:

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    
    public class MathLearning extends JFrame {
        // Variables
        private Container container;
        private JLabel scoreLabel, score;
        public  static JPanel ContainerPanel, panel1, panel2, panel3;
    
        public MathLearning()
        {
            super("Mathematics Learning Game");
    
            //Set new Font..
            Font font1 = new Font("Times New Roman", Font.PLAIN, 20),
                 font2 = new Font("Cambria", Font.PLAIN, 20);
    
            // Create the Container
            container = getContentPane();
    
            // Create Panels and Set Thier Background
            ContainerPanel = new JPanel(new BorderLayout(1,1));
            panel1 = new JPanel(new FlowLayout());
            panel2 = new JPanel(new GridLayout(1,1));
            panel3 = new JPanel();
    
            panel1.setBackground(Color.getHSBColor(0.1f, 0.3f, 0.8f));
            panel2.setBackground(Color.getHSBColor(0.1f, 0.3f, 0.8f));
    
            panel1.setBorder(BorderFactory.createLineBorder(Color.WHITE));
            panel2.setBorder(BorderFactory.createLineBorder(Color.WHITE));
            
            // Label
            scoreLabel = new JLabel("Total Score: ");
            score      = new JLabel();
    
            scoreLabel.setFont(font2);
            scoreLabel.setForeground(Color.DARK_GRAY);
    
            score.setFont(font2);
            score.setForeground(Color.WHITE);
    
            // Add All Components to The Container
            AddCompnents();
            
            // Start The Game by Creating Threads
            startGame();
            
            // set size and location of he window
            setLocation(400, 150);
            setSize(400, 400);
            setVisible(true);
        }
        
        public void AddCompnents()
        {
            container.add(ContainerPanel);
    
            // Panel 1: Top Info Panel(total score, ...).
            panel1.add(scoreLabel);
            panel1.add(score);
    
            // Panel 2: Equation Panel(set from inside the thread).
    
            
            // Container Panel: adds all Panels to The Frame.
            ContainerPanel.add(panel1, BorderLayout.PAGE_START);
            ContainerPanel.add(panel2);
        }
    
        public void startGame()
        {
            MathThread Equation1 = new MathThread(score);
            MathThread Equation2 = new MathThread(score);
    
            /*Thread eq1 = new Thread(Equation1);
            eq1.start();
    
            Thread eq2 = new Thread(Equation2);
            eq2.start();*/
        }
    
        public static void main(String[] args) {
            MathLearning application = new MathLearning();
            application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    
    }

    Thread Class
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class MathThread extends JComponent implements Runnable{
        private int totalScore;
        private int x, y, sign;
        private int YAlign;
        private int result;
        private String calculationNumber;
        private JLabel score;
        private Thread thread;
    
        // Constructor of The Class MathThread
        public MathThread(JLabel sr)
        {
                YAlign = 10;
            totalScore = 00;
                 score = sr;
    
            
            thread = new Thread(this);
            thread.start();
    
            // Generate Random Numbers and Create Random Equation ... 
            createEquation();
        }
    
        public void run()
        {
            System.out.println("Thread Started .. ");
    
            SwingUtilities.invokeLater(new UpdateGUI(score, " " + totalScore));
    
            MathLearning.panel2.add(this);
    
            while(YAlign <= (210))
            {
                YAlign = YAlign + 10;
    
                repaint();
    
                try
                {
                    thread.sleep(300);
                }
                catch(InterruptedException exc)
                {
                    // do something about it ...
                }
    
                repaint();
            }
    
            setVisible(false);  // hide the equation ...
            MathLearning.panel2.repaint();
    
            System.out.println("Thread Finished .. ");
        }
        
        public synchronized void paint(Graphics g)
        {        
            Font font1 = new Font("Times New Roman", Font.PLAIN, 30);
    
            g.setFont(font1);
    
            g.setColor(Color.blue);
            g.drawRect(170, YAlign, 75, 40);
            //g.draw3DRect(170, 10, 75, 40, true);
    
            g.setColor(Color.red);
            g.drawString(" "+ x + " " + calculationNumber + " " + y + " ", 170, (YAlign + 30));
    
            notifyAll();
        }
    
        public synchronized void createEquation()
        {
            // Rabdom Numbers x, y and sign(+ / -)
               x = (int)(10.0 * Math.random());
               y = (int)(10.0 * Math.random());
            sign = (int)(2.00 * Math.random());
    
            if(sign == 0)
            {
                calculationNumber = "+";
                           result = x + y;
            }
            else
            {
                while(y > x)
                {
                    x = (int)(10.0 * Math.random());
                    y = (int)(10.0 * Math.random());
                }
    
                calculationNumber = "-";
                           result = x - y;
            }
        }
    }
    please any help

  2. #2
    NRitH is offline Senior Member
    Join Date
    Feb 2011
    Posts
    118
    Rep Power
    0

    Default

    Of course they are, because you initialized both threads with the same score panel. What do you want instead?

  3. #3
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    You are creating two drawing threads, and they both draw. That's exactly what I would expect. If you want them drawn one at a time, why not use a single thread?

    Also, there are a couple of problems in your design. First, you should put your drawing code in 'paintComponent' rather than 'paint'. Second, you should not synchronize paint (or paintComponent), or anything else that get's called by swing, or you're likely to end up with a deadlock at some point. Strings are immutable, so you don't need to synchronize around 'calculationNumber'.

  4. #4
    AlQassabi is offline Member
    Join Date
    Feb 2011
    Posts
    6
    Rep Power
    0

    Default

    Quote Originally Posted by NRitH View Post
    Of course they are, because you initialized both threads with the same score panel. What do you want instead?
    thank you for replaying

    im not sure if that creates a problem because i want the score panel to update there is a method called invokelater that is why i put score panel as it is..

    what do you think??

  5. #5
    AlQassabi is offline Member
    Join Date
    Feb 2011
    Posts
    6
    Rep Power
    0

    Default

    Quote Originally Posted by toadaly View Post
    You are creating two drawing threads, and they both draw. That's exactly what I would expect. If you want them drawn one at a time, why not use a single thread?

    Also, there are a couple of problems in your design. First, you should put your drawing code in 'paintComponent' rather than 'paint'. Second, you should not synchronize paint (or paintComponent), or anything else that get's called by swing, or you're likely to end up with a deadlock at some point. Strings are immutable, so you don't need to synchronize around 'calculationNumber'.
    thank you toadaly for replaying

    how can i create one drawing thread and run many threads?? is it possible to do it? because it is multithreading and i need about 5 threads in the program so that why i create more than one drawing thread

    in paintComponent do you mean in the threadMath class ??
    i get your points but how to make each thread paints one at a time do i need to use wait and notify methods (i did but i got the same problem)

    any suggestions please ??!!

  6. #6
    AlQassabi is offline Member
    Join Date
    Feb 2011
    Posts
    6
    Rep Power
    0

    Default

    Any Help Please !!!???

  7. #7
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    If you must have multiple painting threads due to a homework requirement, then you need to coordinate the work between them. You could use wait/notify, but it would be better to use a queue.

    If there is no requirment to have multiple paint threads, then you really should consider not doing that. You're making it needlessly complicated.

  8. #8
    AlQassabi is offline Member
    Join Date
    Feb 2011
    Posts
    6
    Rep Power
    0

    Default

    uha, ok toadaly; its not required to do multiple paint thread so i ll make it one paint thread..

    so then i ll run normal threads having the same paint thread right???

  9. #9
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    Sure. A typical swing design constructs a gui and displays it. You register listeners for the various events and react to those events.

    When you incorporate a custom component into the design, that component pasivly waits for something else to call a repaint on it. That repaint is usually called by one of your registered listeners as a result of an action the user has taken (or as the result of a Timer if you need updates independent of user action). There will be multiple threads in action, but you won't need to directly manage them with this approach.

  10. #10
    AlQassabi is offline Member
    Join Date
    Feb 2011
    Posts
    6
    Rep Power
    0

    Default

    yeah i see; thanks a lot toadaly
    that was very helpful


    question: swing by default synchronized. right?

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is online now Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,404
    Rep Power
    20

    Default

    No, just the opposite. All updates/access of Swing component fields/methods should be done on the EDT.
    Lesson: Concurrency in Swing (The Java™ Tutorials > Creating a GUI With JFC/Swing)

    db

    edit: In Java SE 6, some Swing methods are wrongly documented as being thread safe. They aren't. The erroneous documentation has been corrected for Java SE 7.
    Last edited by DarrylBurke; 03-04-2011 at 10:31 AM.

Similar Threads

  1. Running multiple threads on multiple CPU cores?
    By Dosta in forum Threads and Synchronization
    Replies: 2
    Last Post: 09-19-2010, 03:48 PM
  2. Question about running Multiple Threads
    By ferdzz in forum New To Java
    Replies: 2
    Last Post: 06-29-2010, 01:19 PM
  3. keep child threads running after parent thread dies
    By adammyth in forum Threads and Synchronization
    Replies: 2
    Last Post: 01-27-2010, 01:43 PM
  4. Replies: 0
    Last Post: 08-26-2009, 01:03 PM
  5. problem with threads
    By amith in forum Threads and Synchronization
    Replies: 4
    Last Post: 07-10-2008, 07:46 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •