我应该在主要方法中加入什么来使我的程序可以运行?

时间:2015-11-18 10:51:07

标签: java multithreading methods

我的程序需要2个类,它们以确定的间隔生成Threads随机数。

  1. HeltalsGenerator定义Thread,在决定的时间间隔内创建5个随机数,当创建HeltalsGenerator类型的对象时,确定间隔。

  2. SlumpTal1创建并启动Threads类型的HeltalsGenerator

  3. SlumpTal2创建并启动Threads类型的4 HeltalsGenerator数组。

  4. package thread;
    
    class HeltalsGenerator extends Thread {
    
    private int x;
    private int y;
    
    public HeltalsGenerator(int x, int y) {
    
        this.x = x;
        this.y = y;
    }
    
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            int m = (int) (Math.random() * (x + 1) - y);
            System.out.println(m);
        }
        }
    }
    
    class SlumpTal1 {
    
    Thread s1 = new Thread(new HeltalsGenerator(0, 9));
    Thread s2 = new Thread(new HeltalsGenerator(-9, -1));
    
    }
    
    class SlumpTal2 {
    
    Thread t1 = new Thread(new HeltalsGenerator(1, 4));
    Thread t2 = new Thread(new HeltalsGenerator(5, 8));
    Thread t3 = new Thread(new HeltalsGenerator(9, 12));
    Thread t4 = new Thread(new HeltalsGenerator(13, 16));
    
    Thread[] s = {t1, t2, t3, t4};
    }
    
    class Main {
    
    public static void main(String[] args) {
        SlumpTal1 T1 = new SlumpTal1();
        T1.start();
        SlumpTal2 T2 = new SlumpTal2();
        T2.start();
        }
    }
    

    T1.start();T2.start();都会产生错误“无法找到符号:方法start()和SlumpTal1的变量T1”

1 个答案:

答案 0 :(得分:1)

创建一个新类并执行它。

步骤:

  1. 创建一个新文件Main.java(优先于相同的包/文件夹)
  2. 将此代码放在文件
  3. public class Main {
    
        public static void main(String[] args) {
            // do your stuff, ask the user or what you want here, for example:
            SlumpTal1 tail1 = new SlumpTal1();  // execute 2 threads
            tail1.start();
            SlumpTal2 tail2 = new SlumpTal2();  // execute 4 threads
            tail2.start();
        }
    }
    
    1. 执行应用

      • 使用您的IDE(它会自动找到主要方法)
      • 来自command line

        javac Main.java  // compile
        java Main.java   // execute
        
    2. 编辑HeltalsGenerator

      的构造函数
      public HeltalsGenerator(int x, int y) {
          super(x + "-" + y);
      
          this.x = x;
          this.y = y;
      }
      
    3. 注意:

      • 如果所有课程都不在同一个课程中,您需要添加额外的imports