当前位置: 代码迷 >> J2SE >> 高手帮忙看下代码有关问题出在那里
  详细解决方案

高手帮忙看下代码有关问题出在那里

热度:95   发布时间:2016-04-24 13:17:05.0
高手帮忙看下代码问题出在那里
Java code
import javax.swing.*;import java.awt.*;import java.awt.event.*;class GWindows extends JFrame {        public GWindows()    {        super("123");        setSize(246,351);        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        this.setResizable(false);        this.setVisible(true);     }    }class DR implements Runnable{    int i=0;    public void run()    {        System.out.println(i++);        try         {              Thread.currentThread().sleep(100);        } catch (InterruptedException ex)         {              ex.printStackTrace();         }                 }}class DC implements KeyListener{    public void keyPressed(KeyEvent e)    {    }    public void keyReleased(KeyEvent e)    {    }    public void keyTyped(KeyEvent e)    {    }}class G extends JPanel implements Runnable{    Thread thread1,thread2;    DR dr=new DR();    DC dc=new DC();    public G()    {        GWindows gwindows =new GWindows();        gwindows.getContentPane().add(this);        gwindows.addKeyListener(dc);        thread1=new Thread(dr);        thread1.start();        thread2=new Thread(this);        thread2.start();    }    public void paint(Graphics g)    {        super.paint(g);        Color save_color=g.getColor();        g.setColor(new Color(255,255,0));        g.fillRect(0,0,240,320);    }    public void run()     {          while(true)         {              repaint();             try              {                  thread2.sleep(100);             } catch (InterruptedException ex)              {                  ex.printStackTrace();              }          }     }     }public class Test{    public static void main(String[] args)     {        new G();    }}thread1这个线程怎么不会执行i不会持续打印输出


------解决方案--------------------
上面写错了,你是程序忘记写一个for语句了吧.
class DR implements Runnable
{
int i = 0 ;

public void run ( )
{
for(int i = 0 ; i< 100; i++) {
System.out.println ( i ++ ) ;
try
{
String name = Thread.currentThread().getName();
System.out.println ("name ="+name) ;
Thread.currentThread ( ).sleep (1000 ) ;
} catch ( InterruptedException ex )
{
ex.printStackTrace ( ) ;
}
}
}
}
  相关解决方案