日期:2014-05-20  浏览次数:20744 次

高手帮忙看下代码问题出在那里
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 ( ) ;
}
}
}
}