我知道java多線程中的一些基本概念。但現在我想創建5個應該併發工作的線程。如何獲得線程的執行時間?...有人請幫助我深入線程的概念包括方法和目的。java多線程的核心概念
-2
A
回答
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.");
}
}
相關問題
- 1. 核心Java基本概念
- 2. Java線程概念
- 3. 多線程概念
- 4. java中多線程的概念
- 5. Wait()和Notify()概念 - Java多線程
- 6. Java線程概念/演示
- 7. C#:線程和多線程的概念
- 8. 線程概念
- 9. 線程概念
- 10. Quartz.net的Windows服務核心概念
- 11. 多CPU核心中的Java多線程
- 12. 幫助核心數據概念
- 13. 核心日期概念:NSFetchedResultsController與NSManagedObject objectsWithFetchRequest
- 14. iphone/ios - 核心數據關係概念
- 15. C++程序線程概念
- 16. JMS多線程概念與MQ
- 17. 何處使用多線程概念
- 18. 對多線程概念有點困惑
- 19. C#多線程概念問題
- 20. 多線程和多核心
- 21. 概念線程問題
- 22. 線程和塊概念
- 23. 學習線程概念
- 24. 存儲過程概念是否存在於核心數據中?
- 25. java是否有可轉移對象(多線程概念)
- 26. Java ArrayList概念
- 27. Java Array概念
- 28. 概念在Java
- 29. 多線程核心數據
- 30. Java RMI的概念
問題不清楚 – ankit