class a extends Thread { public void run() { for (int i=0;i<=3;i++) { System.out.println("I am a student"); try { sleep(4000); } catch(InterruptedException e){}
} } } class b extends Thread { public void run() { for (int i=0;i<=4;i++) { System.out.println("I am a teacher"); try { sleep(4000); } catch(InterruptedException e){}
} } } public class class14_2 { public static void main(String args[]) { a aaa=new a(); b bbb=new b(); aaa.start(); bbb.start(); } } 这是用Thread类实现的,还用一种用Runnable接口实现的,你回去运行一下。
import java.awt.*;public class class14_5 extends java.applet.Applet implements Runnable//使用接口的双线程 { Thread www; Thread hhh; int i=0,j=0; public void init() { resize(300,300); www=new Thread(this); hhh=new Thread(this); } public void start() { www.start(); hhh.start(); }
public void run() { while (true) { if (Thread.currentThread()==www) { i=i+5; repaint(); try { www.sleep(1000); } catch(InterruptedException ee){} if (i>300) i=0; } else if (Thread.currentThread()==hhh) { j=j+5; repaint(); try { www.sleep(1000); } catch(InterruptedException ee){} if (j>300) j=0; } } }
public void paint(Graphics g) { g.drawString("欢迎来到!", i, 50); g.drawString("欢迎来到!", 50, j); } }
label上面就是一个String啦
然后再repaint();
{
public void run()
{
for (int i=0;i<=3;i++)
{
System.out.println("I am a student");
try
{
sleep(4000);
}
catch(InterruptedException e){}
}
}
}
class b extends Thread
{
public void run()
{
for (int i=0;i<=4;i++)
{
System.out.println("I am a teacher");
try
{
sleep(4000);
}
catch(InterruptedException e){}
}
}
}
public class class14_2
{
public static void main(String args[])
{
a aaa=new a();
b bbb=new b();
aaa.start();
bbb.start();
}
}
这是用Thread类实现的,还用一种用Runnable接口实现的,你回去运行一下。
{
Thread www;
Thread hhh;
int i=0,j=0;
public void init()
{
resize(300,300);
www=new Thread(this);
hhh=new Thread(this);
} public void start()
{
www.start();
hhh.start();
}
public void run()
{
while (true)
{
if (Thread.currentThread()==www)
{
i=i+5;
repaint();
try
{
www.sleep(1000);
}
catch(InterruptedException ee){}
if (i>300)
i=0;
}
else if (Thread.currentThread()==hhh)
{
j=j+5;
repaint();
try
{
www.sleep(1000);
}
catch(InterruptedException ee){}
if (j>300)
j=0;
}
}
}
public void paint(Graphics g)
{
g.drawString("欢迎来到!", i, 50);
g.drawString("欢迎来到!", 50, j);
}
}