我知道java多线程的一些基本概念。但是现在我想创建5个应该同时工作的线程。我怎样才能得到一个线程的执行时间?...有人请帮助我了解线程的深层概念,包括方法和目的。
4 回答
Your question is really unclear. What do you mean by execution time of a thread? When it started vs. when it stopped (wall time) Or how long it was actually running, not including times it was on hold (i.e., CPU time)?
Take a look at Monitor cpu usage per thread in java?
BTW, Threading isn't something you can simply learn from a StackOverflow answer.
The official guide to Java explains concurrency quite well: http://docs.oracle.com/javase/tutorial/essential/concurrency/
The book "Java Concurrency in Practice" is even better.
Make a proxy
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));
}
}
}
and use it
new Thread(new Proxy(task)).start();
像这样的代码可能很有用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.");
}
}
您可以使用以下方法
ThreadMxBean接口
您可以使用获取实例
ManagementFactory.getThreadMXBean();
之后你可以调用一个方法
getThreadCpuTime(Thread.currentThread().getId());
所以你的代码看起来像
ManagementFactory.getThreadMXBean.getThreadCpuTime(Thread.currentThread().getId());
有关更多详细信息,请参阅文档