如何在Thread中访问Runnable对象的字段

问题描述 投票:0回答:1

我正在尝试获取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个回答
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()将阻塞,直到你的线程完成运行,希望我帮助

© www.soinside.com 2019 - 2024. All rights reserved.