Is there a method in Java where it can tell me the age of a running thread? I want to be able to print out the time a particular thread does something.
I can't think of anything that exists, but it would be easy enough to subclass Thread, add a timestamp variable, add a getTimestamp() method, and simply have it fill in the time value at the start of the run() method or in the constructor.
run GetTimeStamp() at the beginning of the thread, then again when you want to know how long the Thread has been running, then subtract one from the other.
You missed a few key points in your ThreadTest class, and in the actual usage of the getTimeStamp() idea.
You wanted to know when a thread starts, so that's what this does.
To call it, you would use thread1.getTimeStamp() or thread2.getTimeStamp()
This now let's you know when each of the threads entered the run method.
class ThreadTest extends Thread
{
long timeStamp = 0;
public long getTimeStamp() {
return timeStamp;
}
public void run()
{
//loads the starting time of this thread into timeStamp
timeStamp = System.currentTimeMillis();
System.out.println( "time for " + getName() + " is " + System.currentTimeMillis() );
I want a int variable that is shared by several threads. If one thread increments the variable all threads will see change. How do I accomplish this? In C++ it's a matter of passing pointers, but I don't know how in java.
I have a class with a synchronized method and another that isn't. If a thread accessess the synchronized method it gets a lock? Can another thread come in and access the non-synchronized method at same time or is the entire class blocked?
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.