编写三个线程分别显示各自的运行时间,第一个线程每隔1秒钟运行一次,第二个线程每隔5秒钟运行一次,第三个线程每隔10秒钟运行一次。
源代码
线程类Sleep类
package experiment.exp8;
public class Sleep extends Thread{
public int SleepTime=0;
public long time=0;
public int i=0;
public int k=1;
public Sleep(String s) {
super(s);
}
public synchronized void run()
{
long start=System.currentTimeMillis();
while(i==0)
{
System.out.println(Thread.currentThread().getName()+"正在运行第"+k+++"次");
try
{
sleep(SleepTime);
}
catch(InterruptedException e)
{
e.getStackTrace();
}
long end=System.currentTimeMillis();
time=time+end-start;
}
}
}
测试类Sleep_test类
package experiment.exp8;
import java.util.Scanner;
public class Sleep_test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Sleep s1=new Sleep("线程一");
s1.SleepTime=1000;
s1.start();
s1.i=sc.nextInt();
System.out.println("线程一结束运行,启动线程二");
Sleep s2=new Sleep("线程二");
s2.SleepTime=5000;
s2.start();
s2.i=sc.nextInt();
System.out.println("线程二结束运行,启动线程三");
Sleep s3=new Sleep("线程三");
s3.SleepTime=10000;
s3.start();
s3.i=sc.nextInt();
System.out.println("线程三结束运行");
System.out.println("线程一运行时间:"+s1.time+"\n"+"线程二运行时间:"+s2.time+"\n"+"线程三运行时间:"+s3.time);
sc.close();
}
}