多线程和Swing

时间:2012-03-14 11:24:25

标签: java multithreading swing graphics awt

我在并行运行两个线程时遇到问题。每个线程都可以单独运行。我的要求是显示10个球,如果value0则为红色球,如果value1则为绿色球,则为一个接一个。 value中的数据是从包含01 s的数组中接收的。我需要一起运行16个这样的线程。我目前正在尝试两个。

package pkg2;
public class mainClass {

public static void main(String[] args) {
    Intermediate frame = new Intermediate();
    }
}

主类调用中间类

package pkg2;

import java.awt.Color;
import javax.swing.*;

public class Intermediate extends JFrame {

    public Intermediate() {
        DivScreen ob = new DivScreen();
        ob.setBackground(Color.black);
        ob.divScreen1(16);
        add(ob);
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setSize(1370, 740);
        setResizable(false);
    }
}

在中间类中,DivScreen类的对象在所有线程和GUI部分完成的地方完成。

package pkg2;

import java.awt.*;
import javax.swing.*;

public class DivScreen extends Canvas implements Runnable//,ActionListener
{

    Thread t1[];            //threads
    int i, j;               //n=total no. of lines, i=no. of rows, j=no of columns
    public static int x;    // x is now global variable
    public static int i1 = 0, i2 = 0;   //to continue fetching data from last entry
    public static int c1 = 0, c2 = 0;   // to check whether line is working or not
    public static int y1, y2;   // to show red or green balls
    public static int k1 = 0, k2 = 0;   //to draw 10 balls
    int green, blue, red;   //variables for color of lines
    int arr1[] = {1, 1, 0, 1};
    int arr2[] = {1, 0, 1, 0, 1, 0};

    public DivScreen() //default.  constructor
    {
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Font f = new Font("Arial", Font.BOLD, 30);
        setFont(f);
    }

    public void divScreen1(int m) {
        t1 = new Thread[2]; //HERE WE HAVE TO PAAS n AS SIZE OF THREAD ARRAY 
        // BUT JUST TO CHECK ITS WORKING WE ARE USING 2 THREADS 
        for (int i = 0; i < 2; i++) {
            t1[i] = new Thread(this, (i + 1) + "thread");
            t1[i].start();
        }
    }

    public void paint(Graphics g) {
        g.setColor(Color.white);

        for (int i = 1; i < 4; i++) {
            j = i;                              //j is for horizontal lines
            g.drawLine(i * 342, 0, i * 342, 740); //i is for vertical lines
            g.drawLine(0, j * 185, 1370, j * 185);
        }
        if (x == 1) {
            g.setColor(Color.GRAY);
            g.drawString("Line 1", 150, 50);
            if (c1 == 0) {
                g.drawString("Line is not in use", 30, 150);
                g.setColor(Color.black);
                g.fillRect(45, 90, 200, 30);
            } else {
                g.setColor(Color.black);
                g.fillRect(30, 120, 250, 30);
                if (k1 < 10) {
                    if (y1 == 0) {
                        g.setColor(Color.red);
                    } else {
                        g.setColor(Color.green);
                    }
                    g.fillOval(50 + 20 * (k1++), 100, 15, 15);
                } else {
                    k1 = 0;
                    g.setColor(Color.black);
                    g.fillRect(45, 90, 200, 30);
                }
            }
        }

        if (x == 2) {
            g.setColor(Color.gray);
            g.drawString("Line 2", 460, 50);
            if (c2 == 0) {
                g.drawString("Line is not in use", 370, 150);
                g.setColor(Color.black);
                g.fillRect(385, 90, 200, 30);
            } else {
                g.setColor(Color.black);
                g.fillRect(370, 120, 250, 30);
                if (k2 < 10) {
                    if (y2 == 0) {
                        g.setColor(Color.red);
                    } else {
                        g.setColor(Color.green);
                    }
                    g.fillOval(390 + 20 * (k2++), 100, 15, 15);
                } else {
                    k2 = 0;
                    g.setColor(Color.black);
                    g.fillRect(385, 90, 200, 30);
                }
            }
        }
    }

    public void update(Graphics g) {
        paint(g);
    }

    public void run() {
        while (true) {
            if (Thread.currentThread().getName().equals("1thread")) {
                x = 1;
                int value = 0;              // to get value from array              
                while (i1 < 4) {
                    c1 = 1;
                    value = arr1[i1];   //valid is a value containing 1 or 0 
                    i1++;               // 1 implies product is OK, 0 implies product not OK

                    System.out.println(value);
                    if (value == 1) {
                        y1 = 1;         // we will check its value in paint() function
                    } else {
                        y1 = 0;
                    }
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            repaint(0, 0, 342, 185);
                        }
                    });


                    try {
                        Thread.sleep(200);
                    } catch (Exception e) {
                        System.out.println(e);
                    }
                }

                c1 = 0;
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        repaint(0, 0, 342, 185);
                    }
                });


                try {
                    Thread.sleep(200);
                } catch (Exception e) {
                    System.out.println(e);
                }
            }

            if (Thread.currentThread().getName().equals("2thread")) {
                x = 2;
                int value2 = 0;                 // to get value from arr2[]

                while (i2 < 6) {
                    c2 = 1;
                    value2 = arr2[i2];
                    i2++;
                    System.out.println(value2);
                    if (value2 == 1) {
                        y2 = 1;
                    } else {
                        y2 = 0;
                    }
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            repaint(342, 0, 342, 185);
                        }
                    });

                    try {
                        Thread.sleep(200);
                    } catch (Exception e) {
                        System.out.println(e);
                    }

                }

                c2 = 0;
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        repaint(342, 0, 342, 185);
                    }
                });

                try {
                    Thread.sleep(200);
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
    }
}

如果你能找到答案,请回复。 感谢。

1 个答案:

答案 0 :(得分:1)

小心多线程。

只是一个例子:

  • x是一个静态变量,它将被两个线程更改并在paint()中使用。在开始时或执行paint()期间,您无法保证x的状态。线程可能会随意更改它。

我建议您阅读有关线程和并发性以及如何管理它的更多内容但我会说最大的问题是程序本身的设计。你究竟想要实现什么?为什么需要多线程?如果要对绘制内容进行大量计算,可以使用多个线程进行这些计算,但绘制方法应该以同时安全的方式接收该信息。只有一个线程应该执行绘制作业,并且应该锁定绘制期间使用的信息。