【问题标题】:Why it different when the start() command is placed? [closed]为什么放置 start() 命令时会有所不同? [关闭]
【发布时间】:2020-02-09 17:49:33
【问题描述】:

我试图把 f1.start();主命令(当我用 B 标记它时) 它给了我一个错误,我试图理解为什么。 所以我把它改成了现在的位置,我的程序按原样编译, 我只是好奇为什么。 谢谢。

package Try;

import java.util.Random;
import java.util.Scanner;

public class Foo1 extends Thread {

    private int min_, max_;
    Foo1(int max, Integer min) {

    max_ = max;
    min_ = min.intValue();
    }

    public void run() {

        Random rand_gen = new Random();
        while(true) {
            try {
                Thread.sleep(rand_gen.nextInt(max_-min_) + min_);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println("you got new message");
        }
    }

    public static void main(String[] args){

        System.out.println("Insert 1 to start"); // C

        Scanner sc = new Scanner(System.in); // D

        int i = sc.nextInt();

        if (i == 1) {
            Foo1 f1;
            //f1.start(); // B
            int max = 1000;
            Integer min = new Integer(1000);
            Foo1 f2 = new Foo1(max, min);
            f1 = f2; // A
            f1.start();
        }
    }
}

【问题讨论】:

  • 当你问为什么它给你一个错误时,你为什么不告诉它到底是什么错误?

标签: java multithreading memory


【解决方案1】:

因为您声明了f1,但您没有使用Foo1 的实例初始化变量。

在这里查看更多信息:A Guide to Creating Objects in Java

【讨论】:

  • 谢谢!也许你知道我还有一个问题。 - 为什么在 //C 行,即使没有 System 类型的对象,也可以访问方法 println()?我知道它与链接过程下的类初始化有关,但不能解释为什么..
  • @LorinSherry 这里有解释:System.out.println
  • 谢谢,我读到了,因为 System 是 final 类?
  • @LorinSherry 这与决赛无关。这是因为outSystem静态 变量。静态变量(和函数)不需要声明它们的类的实例来访问(或调用)。非静态方法println 是变量out 上的一个方法,它包含一个PrintStream 实例。更多阅读:static keyword in java
  • @LorinSherry,您提出的问题——//B 出现错误消息的原因——已得到解答。如果您还有其他问题,那么您应该单独发布这些问题,而不是尝试在此处的 cmets 中继续对话。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 2021-01-03
  • 2014-11-17
  • 2017-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多