2013-10-03 146 views
-2

我知道java多线程中的一些基本概念。但现在我想创建5个应该并发工作的线程。如何获得线程的执行时间?...有人请帮助我深入线程的概念包括方法和目的。java多线程的核心概念

+0

问题不清楚 – ankit

回答

2

你的问题确实不清楚。线程的执行时间是什么意思?它何时开始与何时停止(挂墙时间)或实际运行多长时间,不包括它处于保持状态的时间(即CPU时间)?

看看Monitor cpu usage per thread in java?

BTW,线程是不是你可以简单地从StackOverflow的答案学习。

官方指导价为Java解释并发相当不错: http://docs.oracle.com/javase/tutorial/essential/concurrency/

书中的“Java并发编程实践”,甚至更好。

+0

请原谅我的无知。我仍然不明白我们如何才能获得线程的实际执行时间? – TheLostMind

0

您可以使用

ThreadMXBean的接口

的方法,你可以使用

ManagementFactory.getThreadMXBean(); 

后的情况下,你可以调用一个方法

getThreadCpuTime(Thread.currentThread()。getId());

使你的代码看起来像

ManagementFactory.getThreadMXBean.getThreadCpuTime(Thread.currentThread().getId()); 

详细内容见Docs

1

做代理

class Proxy implements Runnable { 
    final Runnable target; 

    Proxy(Runnable target) { 
     this.target = target; 
    } 

    public void run() { 
     long t0 = System.currentTimeMillis(); 
     try { 
      target.run(); 
     } finally { 
      System.out.println(Thread.currentThread() + " execution time = " + (System.currentTimeMillis() - t0)); 
     } 
    } 
} 

,并用它

new Thread(new Proxy(task)).start(); 
0

像这样的代码可能是有用的http://blog.sheidaei.com/2013/06/simple-thread-example-in-java.html

您可以使用System.currentTimeMillis()而不是System.out.println()来获取线程的执行时间。

/** 
* Created with IntelliJ IDEA. 
* User: shahin 
* Date: 6/5/13 
* Time: 11:32 PM 
* To change this template use File | Settings | File Templates. 
*/ 
public class SimpleThread implements Runnable{ 

    public SimpleThread(String simpleName) { 
     this.simpleName = simpleName; 
     System.out.println(">>> Constructor for " + getSimpleName()); 
    } 

    public String getSimpleName() { 
     return simpleName; 
    } 

    public void setSimpleName(String simpleName) { 
     this.simpleName = simpleName; 
    } 

    private String simpleName; 
    @Override 
    public void run() { 
     System.out.println(" >> "+getSimpleName() + " started."); 
     try { 
      Thread.sleep(100); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. 
     } 

     System.out.println(" >> "+getSimpleName() + " stopped."); 
    } 

    public static void main(String args[]) 
    { 
     System.out.println("Main Thread started."); 

     SimpleWaitNotifyThread simpleThread; 
     Thread thread; 
     for(int i=0;i<5;i++) 
     { 
      simpleThread = new SimpleWaitNotifyThread("Thread "+(i+1)); 
      thread = new Thread(simpleThread,"Thread "+(i+1)); 
      thread.start(); 
     } 

     System.out.println("Main Thread finished."); 
    } 
}