gpt4 book ai didi

java - 线程的非参数化构造函数做什么以及如何在启动它之前调用它的 sleep 方法

转载 作者:行者123 更新时间:2023-12-03 12:59:22 26 4
gpt4 key购买 nike

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 秒的延迟)?非参数化构造函数在哪里使用,当我们不传递扩展Thread类或实现Runnable接口(interface)的类作为参数时,jvm如何在内部调用run方法?

最佳答案

Here,how can the thread's sleep method be called before it is started.


Thread.sleepstatic方法, Causes the currently executing thread to sleep .即此代码导致主线程 hibernate 。如果你用 t.sleep(1000) 调用它并不重要或 Thread.sleep(1000) - 结果是一样的。
Thread此代码中创建的实例(由 Thread t = new Thread() )从未启动,因此只有一个线程在运行。

Also this code gives output on every second. How is this possible when threads run parallel with main thread.How can that affect the output(ie introduce a delay of 1second).



正如我所说,这里只有一个线程在运行——主线程。 Thread.sleep(1000)导致该线程 hibernate 1 秒。

Where is non parameterized constructor used,how can the run method be called internally by jvm when we don't pass the class which either extends Thread class or implements Runnable interface as a parameter



如果您将调用添加到 t.start()在这段代码中,它将执行 Threadrun()方法,它什么都不做,正如 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的无参数构造函数,因此构造函数仍然有用。

关于java - 线程的非参数化构造函数做什么以及如何在启动它之前调用它的 sleep 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46630780/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com