【问题标题】:How can I access the fields of the Runnable object within my Thread如何访问我的线程中的 Runnable 对象的字段
【发布时间】:2019-08-08 03:55:50
【问题描述】:

我正在尝试获取 CPU 执行上下文切换所需的时间,因此我有一个类以纳秒为单位占用系统时间,我将其放入一些线程中,但我需要获取这些数字并对其执行计算但是我不知道如何访问它。

这是我的主要功能。

 public class GroupNinePipe{
    public static void main(String[] args)
    {
        Thread t1 = new Thread(new OSProj2("Thread1"));
        Thread t2 = new Thread(new OSProj2("Thread2"));
        Thread t3 = new Thread(new OSProj2("Thread3"));
        Thread t4 = new Thread(new OSProj2("Thread4"));
        Thread t5 = new Thread(new OSProj2("Thread5"));
        Thread t6 = new Thread(new OSProj2("Thread6"));

        OSProj2 n = new OSProj2("Thread 8");



        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();

    }
}

课程占用系统时间。

    public class OSProj2 implements Runnable {
    String name;
    long time;

    public OSProj2(String x)
    {
        name = x;


    }

    public void run()
    {
        try{
            time = System.nanoTime();
            System.out.printf("%s sys time: %d\n", name, time);
            this.getTime();


        }
        catch (Exception e){}
    }

    public long getTime()
    {
        return time;
    }
}

我知道类的名称是 Pipe,但我没有使用。

【问题讨论】:

    标签: java multithreading concurrency operating-system java-threads


    【解决方案1】:

    我不知道这是否是正确的方法,但是你的代码变成了这样

        Runnable osProj2 = new OSProj2("Thread1");
        Thread t1 = new Thread(osProj2);
        t1.start();
    
        try {
            t1.join();
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
         System.out.println(osProj2.getTime()); // for example
    

    t1.join() 将阻塞,直到您的线程完成运行,希望对我有所帮助

    【讨论】:

      猜你喜欢
      • 2011-01-19
      • 2020-08-03
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多