有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

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

    Thread.sleep是一种static方法,它Causes the currently executing thread to sleep。i、 e.此代码导致主线程休眠。不管你用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)使该线程休眠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的无参数构造函数,因此该构造函数仍然有用