Thread's 'getId()' Problem

Hello All,
I try to use the ID of threads withoud any success.
I declare two threads in this way:
Thread threads[] = new Thread[2];
threads[0] = new Thread();
threads[1] = new Thread();
for(int i=0;i<2;i++)
  threads.start();
then, when I look for its ID's, I get for both '1' (is it the 'main' ID?)
// from the method which the thread has activated
System.out.printf("Thread's ID is: %d",Thread.currentThread().getId());Is there any way to change the ID of a thread?
Thanks :)
Message was edited by:
drortrie@

I try to implement Peterson Algorithm (which uses the threads' ID)
I extended 'Thread' class, here's 'start()'
  public void start()
         int i=0;
          while (i<5)
          {     counter.inc();     
               i++;
    }I have a shared counter for both threads. (I have a constructor which handle it)
class Counter
     long value=0;
                      Peterson lock = new Peterson();
     public void inc(){
          lock.lock();
          try{
                    long temp;
          temp = value+1;
          value = temp;
          } finally{
          lock.unlock();}
}and the 'lock()' code:
public void lock(){
          int i = (int) Thread.currentThread().getId();
          System.out.println(i);
          int j = 1-i;
          flag[i] = true;
          victim = i;
          while (flag[j] && victim==i){}; // WAIT HERE
     }Probably you are right, because I get '1' in 'System.out.printf(i)'.

Similar Messages

  • Thread pool executor problem

    When using a thread pool executor (java.util.concurrent.ThreadPoolExecutor) to limit the number of threads executing at a time, the number of threads running still exceeds the limit number.
    This is the code:
    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 20, TimeUnit.SECONDS, new LinkedBlockingQueue());
    The number of tasks in my program are 4, so i always have 4 threads running, although i limited it to 3.
    Can anyone help me with this problem? Or can u propose another solution to limit the number of running threads? By the way, i also tried using a newFixedThreadPool() and got the same problem.
    Thx.

    The number of tasks in my program are 4, so i always
    have 4 threads running, although i limited it to 3.How do you know that there are 4 threads running? If you're generating a JVM thread dump, you're going to see threads that are used internally by the JVM.
    Here's a simple program that creates a fixed-size threadpool and runs jobs. It limits the number of concurrent threads to 3. Compare it to what you're doing, I'm sure that you'll find something different. Also, verify that you're not creating threads somewhere else in your program; all of the ThreadPoolExecutor threads will have names of the form "pool-X-thread-Y"
    import java.util.concurrent.Executors;
    import java.util.concurrent.ExecutorService;
    public class ThreadPoolTest {
        public static void main(String[] args) {
            ExecutorService pool = Executors.newFixedThreadPool(3);
            for (int ii = 0 ; ii < 10 ; ii++) {
                pool.execute(new MyRunnable());
            pool.shutdown();
        private static class MyRunnable implements Runnable {
            public void run() {
                log("running");
                try {
                    Thread.sleep(1000L);
                catch (InterruptedException e) {
                    log("interrupted");
            private void log(String msg) {
                System.err.println(
                        msg + " on " + Thread.currentThread().getName()
                        + " at " + System.currentTimeMillis());
    }

  • Recorded show not always playing back. New 2013 thread to ongoing problem

    We have two Motorola QIP7232 2 DVR/Receivers. Since we got them back in March of 2012 we have had sporadic issues where programs that show to be recorded (30 minutes, 60 minutes, etc), won't play back.  The DVR simply reverts back to live TV as if we've canceled the playback. One receiver was replaced in April 2012 but the problem still continues off and on to as recently as of this post.
    This happens on BOTH receives. Neither receiver is even near capacity. Maybe 20% at the most at any time.  Since we've had a receiver replaced - and it continues to happen on both DVRs - and there's another three year old thread full of the same complaint, I can only assume it's either defected equipment or defected service.
    Verizon? Any answers?

    I have had the same problem on the Cisco 435hdc box and an external dvr for months.  Fios tech just had me run the autofix which I had already tried and this didn't help.  It happens randomly and is very annoying.  It also happens when I record a show and want to watch it from the beginning while it is still recording it.  It does not allow me to watch from the beginning of the recording it only goes back about 30 minutes.

  • Thread safe architecture problem

    I am developing a app that is utilizing a proxy pattern to "wrap" instances of a few classes. The consumer of the proxy then does not need an instance of the inner class and the inner class is shared among all of the proxy consumers. However, I need the ability for the underlying class to be changed as needed ( reloaded through a ClassLoader to be more precise ). The problem is that I am trying to move this into a multi-threaded environment and am running into a few problems. I know that synchronization could solve my problems, but that will adversely affect the performance because only one thread will be able to execute the code any give time given that all of the proxies use the same underlying class. The reason that the proxies all wrap the same class is to eliminate constantly creating instances to handle the processing. (they are referenced from jars at runtime and use reflection to instantiate them)
    Does any one have any suggestions on how to better structure this?

    There are probably better ways, but one simple way would be to use a ReadWriteLock. In the proxy: aquire the read lock upon invocations to the underlying "real" instance. When you want to switch implementations, aquire the write lock (will wait for all readers to finish, and then prevent any readers from executing while you swap in your new state).
    This way, if your old implementation needs to be "shut down", you can be sure that no one is relying on it when you do so. On the other hand, it doesn't prevent concurrent usage of the underlying instance when it's in service.
    See java.util.concurrent.locks.ReadWriteLock (java 1.5) or doug leas util.concurrent for java versions before that

  • ThreadInfo's getThreadId() == java.lang.Thread's getId() ?

    Hi Folks
    I am trying to add MBean to show CPU consumption of various threads in my application.
    The threads created during the course of the application execution are maintained in a vector list.
    In my instrumentation code, I use this list of threads and
    a) iterate over each Thread instance and get its thread id ( thread.getId() )
    b) Using this long value, I determine the CPU consumption of this thread as :
    ThreadMXBeanInstance. getThreadCpuTime(threadId)
    However this does not seem to be giving me the correct value.
    On debugging using a generic program, where I print the thread ID , name, CPU consumption of all the threads in the JVM, as :
    ThreadMXBeanInstance.getAllThreadIds()
    for( each ThreadInfo...)
    //print attributes using ThreadInfo.getThreadName(..)..getThreadId(..)...etc..
    the thread ID printed by ThreadInfo.getThreadId() seems to be always +1 + the threadID got as in (a))+.
    Please let me know if you can throw some light on the above subject?
    ps : I am using Java 6, u10 on a WINXP, SP2 + 2CPU Intel Core processor with 2 GHz & 2GB memory.
    Great Thanks in advance.

    Hi,
    Are you sure you haven't made a mistake somewhere?
    Here is a small program that iterates over the threads and print their name and thread id has obtained from Thread and ThreadInfo. I've run it on JDK 6u10 and as you can see the information match. What do you get if you run it on your install? (hint: run it with -Dcom.sun.management.jmxremote to get the same results than I).
    Here the program:
    package threadid;
    import java.lang.management.ManagementFactory;
    import java.lang.management.ThreadInfo;
    import java.lang.management.ThreadMXBean;
    * @author dfuchs
    public class Main {
         * @param args the command line arguments
        public static void main(String[] args) {
            // TODO code application logic here
            final ThreadMXBean tmb = ManagementFactory.getThreadMXBean();
            final Thread[] ts = new Thread[tmb.getThreadCount()];
            ThreadGroup tg = Thread.currentThread().getThreadGroup();
            while (tg.getParent()!=null) {
                tg = tg.getParent();
            tg.enumerate(ts,true);
            for (Thread t : ts) {
                if (t==null) continue;
                final ThreadInfo ti = tmb.getThreadInfo(t.getId());
                System.out.println(t.getName()+"[id="+t.getId()+"]: name=" +
                        ti.getThreadName()+", id="+ti.getThreadId());
    }Here is the output:
    Reference Handler[id=2]: name=Reference Handler, id=2
    Finalizer[id=3]: name=Finalizer, id=3
    Signal Dispatcher[id=4]: name=Signal Dispatcher, id=4
    RMI TCP Accept-0[id=9]: name=RMI TCP Accept-0, id=9
    main[id=1]: name=main, id=1Hope this helps,
    -- daniel
    [http://blogs.sun.com/jmxetc|http://blogs.sun.com/jmxetc]

  • Thread Status Icon Problem

    Hi,
    A problem that I have been facing for quite a while now is that several threads appear with the status icon which means that "Threads whose contents have changed since my last visit (semi orange icons)" but the issue is that I have never visited those threads. So how come they are marked with such a status (they should just be white icons).
    Please check this out
    Regards

    A problem that I have been facing for quite a while
    now is that several threads appear with the status
    icon which means that "Threads whose contents have
    changed since my last visit (semi orange icons)" but
    the issue is that I have never visited those threads.
    So how come they are marked with such a status (they
    should just be white icons).Mmmm shouldn't then they be orange if youv'e never visited them?
    OK I also sometimes have problems, I log in and got a big list of unread or semi-unread threads. And suddenly somewhere in the middle of all them one or two that are white showing that I've completely read them. But it is not possible, unless of course someone other is not working under my account which I hope is not true ;)
    Probably someone just edited the post and it doesn't mean that thread has been updated?
    Anyway to be frank for me this possible bug is on a very low priority because it happens quite rare and the problems coming out of this are quite tiny. I'd classify this bug as "cosmetic" ;)
    Gints Plivna
    http://www.gplivna.eu

  • Mail.app "Threaded view" algorithm problem

    Hello,
    I noticed that there is an issue with "Threaded View" feature in mail.app :
    - First : i think the algorithm gathers emails in threaded view by "Subject"
    - Then the algorithm fall-back to the In-Reply-To and Message-Id headers
    Is there a way to disable the first "gather by subject" feature ? It's annoying because, for example, every mail with subject "Hello !" are threaded, even if there're not related...
    I looked in some com.apple.mail.plist if found, but nothing seemed to be related to this function...
    Thanks.
    Damien

    I, for one, would be interested in hearing what the problem actually is.

  • Thread execution time problem

    Hi everyone.
    I�m developing an application that creates multiple threads, does certain calculations, and runs a couple programs.
    The problem is: for some reason, the time that takes to run each thread tends to increment as the number of threads increments.
    That is, for 2 threads the time is x for 4 is x + n, and so on.
    I�d checked that every thread is doing the same (with few differences that not influences in a reasonable fashion), and that, skipping the external programs execution, the problem doesn�t exist. Moreover, there are no inter thread communication.
    My questions: there is any way in which I can reduce the amount of time?
              There is some reason for the amount of time the external process called takes to run to increment? (I checked that if I not call those programs the amount of time each thread takes to execute is near 0 millisecs).
              Something like Windows limits the use of a program multiple times, or something like that.(yes i have only tested it in Windows environment, and yes, the external programs i use are posix compliant)
    The actually time is about 120 secs., and I have to cut it to, at least, aprox. 40.
    A thread alone can run in less than 30 secs., in the worst case.
    Thanks in advance.

    Now imagine that most of the tasks involve fetching
    something from the refrigerator. Even if you have
    multiple chefs in the kitchen, they will, unless
    scheduled properly, all be contending to open the
    door and reach inside.I think that could be the case. All the threads are trying to execute the same archive. As far as I remember, a file isn't locked if it is accessed for reading (or executing) only, but, on the other hand, you're right, there is only one refrigerator on this kitchen, and too many chefs.
    Something else attracted my attention about this. When I run my project, there are two things that grow considerably: first the CPU's usage, and second, the amount of memory each of the external process called by my program consumes I think this could be related with my problem.
    Again: I ran my project commenting the calls to Runtime.exec(�command�) and the time dropped significantly. Running normally, the threads tend to increment their time of execution. Lets say the first thread takes to execute X seconds, the nth thread will take X plus M. In the test I ran, the first thread lived for 30 seconds and the last (150th) lived for about 130 seconds. Without the calls to Runtime.exec() the first threads lived for 0 milliseconds and the last(150th) lived for 6 milliseconds. Therefore, the CPU�s overhead for everything else isn�t the problem here, I think.
    I tried something else to discard the problem of the file access:
    I created ten copies of the ping program in a directory other than the system default, and called them �ping1�, �ping2�, and so on.
    Then, I created a program that creates some threads and executes a ping through a call to the program pingN (with Runtime.exec(), again), so each thread will access a different file (the first thread access ping1, the second ping2 �), and so, the bottle neck problem on the file system shouldn�t happen. But that hasn�t changed anything. With the calls to Runtime.exec() the execution time goes to the clouds, and without it, it�s near zero. And neither is fault of the ping, the I set the timeout to 3 seconds and the retries to 4, so the max amount of time it�ll take to execute is about 12 seconds, but it takes 40+-

  • Posting Threads causing server problems too?

    I don't feel sorry for apple at all releasing everything in 24 hours, but I think threads are probably not helping either, but then again I think different server's for web vs. itunes.

    Good grief, if they're using the same servers for these boards as they are for their iTunes hosting, they have bigger problems than some ticked off customers.

  • AirTime / Threads and resulting problems

    Hi,
    i ve written something like a proprietary webservice to authenticate a user. So consider this code:
            MyHTTPRequest request = new PlayerRequest("authenticateLogin");
            request.addParameter("login", playername);
            request.addParameter("password", password);
            request.execute();
            if (!request.isError()) {
                Player[] playerArray = (Player[]) request.createObjectsFromHTTP();
                player = playerArray[0];
            } else {
                player = null;
            }execute() fires a new Thread and does the HTTP stuff. Now the Emulator shows the AIRTIME yes/no Screen. It locks because isError() contains a join(), this is because isError() must wait for the HTTP connection to finish to see what happened.
    When i leave out the join() in the isError() method, i can answer the yes/no screen, but then my isError() gets a NullPointer, because the request is not finished.
    So i have a situation, where i cant go on in my code before the HTTPRequest is ended, but i must be able to answer the yes/no screen.
    I tried several things like a loop in the code above which asks if the thread from PlayerRequest is still running but as soon i do something like this, i got my deadlock on yes/no screen again.
    Any suggestions?

    thats exactly the problem why you have to use Threads. The main thread has first to be finished, before the networking thread can be started. By using join() you make the use of Threads obselete since this must be processed sequentially (because the main thread waits for the networking thread, in your implementation). Finally, for this what you want to do using threads is senseless, but they are mandatory for MIDP 2.0.
    Okay, now for the solution ;)
    You have to initiate the processing of the result from your networking thread. That means the main thread finishes and does nothing (or displays a gauge or sth). After the networking, the networking thread calls something like "processResult()" and thus gives the control back to the main thread. This is the principle of using threads: that they can work asynchronously and (more or less) independent from another.
    hth
    Kay

  • Rather complicated (possibly!) threading/event handling problem...

    OK, so here's a good question to ask for my first post to this site!
    My current "project" is a GUI applet that does real-time interactions on a set of objects and user input. I'm using double buffering, event handling (from the keyboard) and multiple threads to handle the categories of "user input and graphics" and "world state updating." Here is a rough overview of how the program is layed out:
    // keyboard input status class
    class Keyboard extends KeyListener {
       static int[] code = new int[7];            // contains keycodes of interesting keys
       static boolean[] status = new boolean[7];     // status of keys (true=pressed)
       static boolean getStatus(int key) {
          return status[key];
       void keyPressed(KeyEvent e) {
          for(int i = 6; i >= 0; i--)
             if(code[i] == e.code)
                status[i] = true;
       void keyReleased(KeyEvent e) {
          for(int i = 6; i >= 0; i--)
             if(code[i] == e.code)
                status[i] = false;
    // main program applet
    class Program extends Applet implements Runnable {
       static Thread thread;      // main thread of applet
       static Image buffer;         // double buffer for offscreen rendering
       static boolean running;  // flag to indicate status of applet
       void init() {
          buffer = createImage(500, 500);
          // other initializations
       void destroy() {
          // other disposes
       void start() {
          running = true;
          thread = new Thread(this);
          thread.start();
          addKeyListener(new Keyboard());   // begin receiving input
       void stop() {
          running = false;
          if(thread != Thread.currentThread())
             thread.join();    // wait for thread to die before continuing
       void run() {
          double paintTimer = 0;   // timer to suspend painting to buffer until necessary
          double dt = 0;       // difference in time between loops
          while(running) {
             // update timing stuff (dt and paintTimer)
             // update world status
             paintTimer -= dt;      // to decrement painting timer
             if(paintTimer <= 0) {
                paintTimer = 1.0 / fps;    // reset paint timer based on current fps setting
                synchronized(syncObject) {
                   // paint world to buffer
                   repaint();
             Thread.yield();  // to yield time to painting and user input thread
       // this method is only called by the internal thread within the applet
       //  that is responsible for painting and event handling
       void paint(Graphics g) {
          // make sure painting to screen won't conflict with thread that's drawing on buffer!
          synchronized(syncObject) {
             g.drawImage(buffer, 0, 0, null);  // do double buffering...paint buffer to screen
    }So the end result is that it works fine some of the time, but every once in awhile I'll get these strange results where it'll seem as if the internal thread that handles graphics and input will get bogged down or stop responding normally, even with the Thread.yield() call from the main applet thread. I'll get results where the world will continue to be updated correctly, but the user input and onscreen rendering freeze in a particular state for a matter of seconds, and then it seems to regain control for a brief few milliseconds (hence I'll get a quick screen refresh and keyboard state change), and then it'll freeze again. Once this starts happening somewhere in the middle of execution, it continues to happen throughout that runtime session. Sometimes when I force-close the appletviewer I'll get weird native runtime exceptions that seem to occur within Sun's keyboard input manager.
    Almost always it'll run perfectly for many minutes, and then all of a sudden it'll start to freeze up. Every once in awhile it freezes almost immediately after startup. I've run some testcases on it and am pretty confident it has nothing to do with the synchronization or the fact that I create a new applet thread every time the applet is restarted dynamically. Is it something happening within the event thread of the applet that I'm not aware of? Or is it something wrong with the flow of my code? Thanks for any input or help you can give! I'll be happy to send more details if needed.
    Zach

    right before your repaint, putSystem.out.println("Is EDT? "+SwingUtilities.isEventDispatcherThread());if its printing false, then you need to do SwingUtilities.invokeLater( ... );
    and put GUI updating code in the invoke later.

  • Thread stack size problem

    Hi all,
    I am having a multithreaded application and the threads are created with 256 KB thread stack size.
    This application was developed in windows(32 bit) now ported to Solaris 8.
    The same was failed while running because of stack overflow and then the thread stack size is increased to 257 KB then the application is working fine.
    Please anybody suggest me how the same application is working fine in windows with lesser thread stack size?
    Please also suggest me any tool which can be used to get the thread stack details while running the application.
    Regards,
    Velan.R.S

    Hello Farhan
    We had similar issues and we tackled it in a few ways. First you may want to track down what type of memory issues you are hitting, permgen verse heap
    Simple Tomcat updates I would look into
    set your inital memory pool to something like 256 MB
    Up your max to 2 or 3 GB
    if you are having permgen issues i would set the following in your tomcat java options
    -Xrs
    -XX:MaxPermSize=512M
    -XX:+CMSClassUnloadingEnabled
    -XX:+UseConcMarkSweepGC
    -XX:+CMSPermGenSweepingEnabled
    -Djava.awt.headless=true
    I would also look into increasing your treads and adding compression to your 8080 listener
    Tomcat Vertical Scale
    Once you have done the simple tomcat updates if you still have issues you may want to add more tomcat instances and use use a proxy server to load balance them. You can use Apache with mod_proxy or mod_jk. or even a more enterprise solution with an appliance like BigIP f5 or Cisco CSS.
    I would really recommend front your tomcat(s) with Apache and doing a split deploy. Then fronting your apache servers with an appliance load balancer. James Rapp has a great article on how to do this. 

  • Thread start() method problem

    I have a program server-client program that have a lot thread but
    when I called thread.start() method it doesn't return run() method.
    even so my input-output codes is running ( my client program can send data to server program )
    Please help me

    yasinmalli wrote:
    start() method doesn't call run() method of thread when I debug row to rowIt does, but the debugger will only ever follow the flow of the current thread and therefore not step into the run method. Set a breakpoint at the very beginning of your run() method and then step over the start() method, you'll see that the new thread will break exactly at that breakpoint just after start() was executed.

  • Thread's controlling problem

    I created a thread with in a thread. While I am running program, both threads are running at a time. I want to pause the parent thread until the child thread is alive. After the child thread stops then only the parent thread again has to be start. Any answer

    In parent thread, do
    childThread.start();
    childThread.join();
    // more processing
    True. That's better.
    /Kaj

  • Multi-threaded video decoding problem

    I have simple AIR 3.8 application with 2 VideoPlayers:
    <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx"
    applicationComplete="init()"
    showStatusBar="false"
    >
    <fx:Script source="MultiVideoPlayer.as" />
    <s:VGroup width="100%" height="100%" >
    <s:HGroup width="100%" height="100%" id="row1" >
    <s:VideoPlayer width="100%" height="100%" source="assets/2.mp4"/>
    <s:VideoPlayer width="100%" height="100%" source="assets/3.mp4"/>
    </s:HGroup>
    </s:VGroup>
    </s:WindowedApplication>
    Both videos are H.264 Full HD samples.
    I launch application and multi-threaded decoding works fine - all cores are involved and CPU usage is around 70%.
    When I replace source of VideoPlayers with exactly same files programmatically - videos are reloading, but they doesn't play smoothly and multi-threaded decoding isn't working anymore - CPU usage drops to 10%.
    Is there any way  to force use of multi-threaded video decoding when videos are loaded dynamically?

    After some hunting I found a Twitter post confirming that StageVideo on AIR 3.2 is not supported on Desktop.
    But one of the notable features of Flash Player 11.2 is Multi-threaded video decoding.
    Does this mean that standard (non-StageVideo) implementations of Video are now automatically using a separate CPU thread?
    If so, this would be a reasonable workaround for smooth video on Desktop.
    Here's Adobe's description of the feature...very vague.
    Multithreaded video decoding (Windows, Mac OS, and Linux) — The video decoding pipeline is now fully multithreaded. This feature should improve the overall performance on all platforms. Note that this feature is a significant architecture change required for other future improvements.

Maybe you are looking for

  • CS4 not working on Snow Leopard

    I have a macbook pro and i've had it for about almost two years now, got it mid 2009.  I also got the adobe creative suite cs4 with it, and since then it's worked a dream. I just upgraded to Snow Leopard, but before I did I was advised to ring Adobe

  • Home Page Question

    Hi Guys, Appreciate your help on what I assume is an easy solution and probably is a stupid question. There are items on the home page that I would like to delete or move from the 2nd page to the 1st (or vice versa). Can't figure out how to do that.

  • Anyone else seeing glitches on Export of Mpeg files?

    I have seen this problem  2 maybe 3 times on CS5.5 but on CS6 (cloud) I have a major problem with this. Export the same sequence from the timeline such as a :30 sec spot and the glitch is in exactly the same place each time.   If I change the mb/s su

  • R/3 - CRM Data Changes - Suggesions Plz

    Dear Folks There seem to be some changes performed in SAP R/3 that changed employees in CRM so they have no names any more. Workaround to resolve ths issue is - in R/3 - to add a letter to the name of the employee and remove it again with saving in-b

  • HT5037 Upgrading Iphoto to Maverick

    I upgraded my IPhoto on Maverick per Apple'sinstructions.  Now I can't see any of my photos.  Only a dotted outline with the name.  HELP!  HOW DO I GET THEM BACK.