2013-10-03 145 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."); 
    } 
}