java线程的非参数化构造函数做什么?如何在启动它之前调用它的sleep方法
import java.io.*;
import java.util.*;
class queue
{
int q[],f=0,r=0,size;
void insert(int n ){
Scanner in =new Scanner(System.in);
q=new int[10];
for(int i=0;i<n;i++){
System.out.println("\n enter"+i+"element");
int ele= in.nextInt();
if(r+1>10){
System.out.println("\n queue is full\n lost packets"+ele);
break;
}
else{
r++;
q[i]=ele;
}
}
}
void delete(){
Scanner in = new Scanner(System.in);
Thread t = new Thread();
if(r==0)
System.out.println("\n Queue is empty");
else{
for(int i=f;i<r;i++){
try{
t.sleep(1000);
}
catch(Exception e){}
System.out.println("\n leaked packet"+q[i]);
f++;
}
}
System.out.println();
}
}
public class Leaky extends Thread {
public static void main(String[] args) throws Exception {
queue q = new queue();
Scanner src = new Scanner(System.in);
System.out.println("enter the packet to be sent");
int size = src.nextInt();
q.insert(size);
q.delete();
}
}
这是在网络中演示漏桶算法的代码。 在这里,线程的sleep方法如何在启动之前被调用?这段代码每秒钟都会给出输出。当线程与主线程并行运行时,这怎么可能呢?这会如何影响输出(即引入1秒的延迟)?在使用非参数化构造函数的地方,当我们不传递扩展线程类或实现可运行接口的类作为参数时,jvm如何在内部调用run方法
# 1 楼答案
Thread.sleep
是一种static
方法,它Causes the currently executing thread to sleep
。i、 e.此代码导致主线程休眠。不管你用t.sleep(1000)
或Thread.sleep(1000)
来调用它,结果都是一样的在此代码中创建的
Thread
实例(由Thread t = new Thread()
)从未启动,因此只有一个线程在运行正如我所说,这里只有一个线程在运行——主线程
Thread.sleep(1000)
使该线程休眠1秒如果在这段代码中添加对
t.start()
的调用,它将执行Thread
的run()
方法,正如Javadoc所说-If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns
使用无参数构造函数创建
Thread
是没有用的(因为该线程将什么都不做)。但是,如果您创建了一个子类Thread
,该子类重写了run()
方法,那么子类的构造函数可以调用Thread
的无参数构造函数,因此该构造函数仍然有用