2012-03-14 5 views
1

병렬로 두 개의 스레드를 실행하는 데 문제가 있습니다. 각 스레드는 개별적으로 잘 실행됩니다. 내 요구 조건은 value이 빨간 공 인 경우 10 개의 공을 표시하는 것이며, value0이고 녹색 공이 value 인 경우 1이 차례로 표시됩니다. value의 데이터는 0s 또는 1s를 포함하는 배열로부터 수신됩니다. 16 개의 스레드를 함께 실행해야합니다. 저는 현재 두 명으로 노력하고 있습니다.멀티 스레딩 및 스윙

package pkg2; 
public class mainClass { 

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

주요 클래스는 중간 수준의 모든 스레딩 및 GUI 부분 완료, DivScreen 클래스의 객체가되어 중간 클래스에서

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); 
    } 
} 

호출합니다.

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); 
       } 
      } 
     } 
    } 
} 

뭔가가있을 경우 회신을 보내주십시오. 감사합니다. .

+0

JComponent와 Runnable 인 클래스를 가지는 것이 매우 이상하게 보입니다. – toto2

+1

스윙 (예 :'JFrame') 및 AWT (예 : 캔버스) 구성 요소를 섞어서는 안됩니다. 더 빨리 도움을 받으려면 [SSCCE] (http://sscce.org/)를 게시하십시오. –

답변

1

멀티 스레딩에주의하십시오.

예일

:

  • X는 두 스레드에 의해 변경되는 것, 또한() 페인트에 사용되는 정적 변수이다. paint()의 처음이나 실행 중 x의 상태에 대해서는 아무 것도 보장 할 수 없습니다. 쓰레드는 마음대로 변경할 수 있습니다.

스레드와 동시성에 대해 조금 더 읽고이를 관리 할 수있는 방법을 제안하지만 가장 큰 문제는 프로그램 자체의 디자인이라고 말합니다. 달성하려는 것이 정확히 무엇이고 멀티 스레딩이 필요한 이유는 무엇입니까? 페인트 할 대상을 광범위하게 계산하려면이 계산에 대해 여러 스레드를 갖는 것이 좋지만 페인트 방법은 해당 정보를 동시에 안전하게 받아야합니다. 하나의 스레드 만 페인트 작업을 수행해야하며 페인트 중에 사용 된 정보는 잠겨 있어야합니다.