Is there a method in Java where it can tell me the age of a running thread?

watdahel

Golden Member
Jun 22, 2001
1,657
11
81
www.youtube.com
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.
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
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.
 

RaynorWolfcastle

Diamond Member
Feb 8, 2001
8,968
16
81
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.
 

notfred

Lifer
Feb 12, 2001
38,241
4
0
Kilrsat invented the getTimestamp() method. He told you to write a subclass of Thread and add a getTimestamp() method.
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
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() );

try{
System.out.println( getName() + ": is sleeping" );
sleep( (int) ( Math.random() * 5000));
}
catch ( InterruptedException e ) {
System.err.println( e.toString() );
}

System.out.println( "time for " + getName() + " is " + System.currentTimeMillis() );
}


public ThreadTest( String threadName )
{
super( threadName );
}
}
 

watdahel

Golden Member
Jun 22, 2001
1,657
11
81
www.youtube.com
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.
 

Kilrsat

Golden Member
Jul 16, 2001
1,072
0
0
replace:

long timeStamp = 0;

with:

static long timeStamp;

You'll need a long, when dealing with currentTimeMillis().
 

watdahel

Golden Member
Jun 22, 2001
1,657
11
81
www.youtube.com
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?
 

glugglug

Diamond Member
Jun 9, 2002
5,340
1
81
If you cut your network cable in half, do you get twice the bandwidth since there are 2 pieces?

Try this and get back to us.