我编写了一个多线程的小应用程序:实现上下两行字符的左右来回移动。
但程序运行时没有任何效果!
程序如下:
import java.awt.*;
import java.applet.*;public class ThreadString extends Applet
{

public void init()
{

Thread thr1=new Thread(new Thread1());
Thread thr2=new Thread(new Thread2());

thr1.start();
thr2.start();

}
}

class Thread1 extends Canvas
implements Runnable
{ int y1;


public void run()
{
while(true)
{
repaint();
try{Thread.sleep(100);}
catch(InterruptedException e){}
}
}
public void paint(Graphics g)
{
if(y1<0)  y1=200; else y1=y1-10;
g.drawString("hello,java!",y1,20);
}
}
class Thread2 extends Canvas
implements Runnable
{
int y2;
public void run()
{
while(true)
{
repaint();
try{Thread.sleep(100);}
catch(InterruptedException e){}
}
}
public void paint(Graphics g)
{
if(y2>200) y2=0; else y2=y2+10;
g.drawString("hello,java!",y2,40);
}
}

解决方案 »

  1.   

    import java.awt.*;
    import java.applet.*;public class ThreadString extends Applet
    {

    public void init()
    {

    Canvas t1=new Thread1(); //实例化画布的同时启动线程
    this.add(t1);
    Canvas t2=new Thread2();
    this.add(t2);
    }
    }

    class Thread1 extends Canvas
    implements Runnable
    { int y1;

    public Thread1() //添加了构造,用于设定画布大小,并启动线程
    {
    this.setSize(300,150);
    new Thread(this).start();
    }
    public void run()
    {
    while(true)
    {
    repaint();
    try{Thread.sleep(100);}
    catch(InterruptedException e){}
    }
    }
    public void paint(Graphics g)
    {
    if(y1<0)  y1=200; else y1=y1-10;
    g.drawString("hello,java!",y1,20);
    }
    }
    class Thread2 extends Canvas
    implements Runnable
    {
    int y2;
    public Thread2()
    {
    this.setSize(300,150);
    new Thread(this).start();
    }
    public void run()
    {
    while(true)
    {
    repaint();
    try{Thread.sleep(100);}
    catch(InterruptedException e){}
    }
    }
    public void paint(Graphics g)
    {
    if(y2>200) y2=0; else y2=y2+10;
    g.drawString("hello,java!",y2,40);
    }
    }
      

  2.   

    楼上正解,关键是在applet中添加画布并且要设置画布的大小(默认是(0,0))。