0

In java is there some API that helps with retrieval of yielded threads, I was trying to prepare some sample program to learn and see yielding clearly by listing the yielded threads, but couldn't.

One more doubt I have is that once yielded does the thread run again or runs from the point it stopped. As per my observations it starts from same stacktrace as the run is not called over and over again. Is it correct ?

Yielding makes the thread state to runnable but can it be differentiated from other threads that are in runnable state.

Or any other program that clearly states yielded threads. I am putting the sample I am working on too..

public class ThreadYieldDemo implements Runnable {

    Thread t;

    ThreadYieldDemo(String str) throws InterruptedException {

        t = new Thread(this, str);
        System.out.println(" State = "+t.getState()+" "+str);
        t.start();
        System.out.println(" State-1 = "+t.getState()+" "+str);
    }

    public void run() {
        System.out.println("Entry = "+Thread.currentThread().getName()+"  State = "+Thread.currentThread().getState());
        Random random = new Random();
        int next = random.nextInt(10);
        if(next%2==0)
        {
            System.out.println(Thread.currentThread().getName());
            System.out.println("In: "+Thread.currentThread().getState());

        }
        else
        {
            System.out.println(Thread.currentThread().getName()+" yielded...");
            Thread.yield();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("yield = "+Thread.currentThread().getState());
        }   
    }

    public static void main(String[] args) throws InterruptedException {
        new ThreadYieldDemo("Thread 1");
        new ThreadYieldDemo("Thread 2");
        new ThreadYieldDemo("Thread 3");
        new ThreadYieldDemo("Thread 4");
        new ThreadYieldDemo("Thread 5");
    }
} 
4

1 回答 1

0

您不能在代码中执行此操作。

但是您可以使用jstack或分析器,这可能会显示更多详细信息。但我仍然认为它不会告诉你是否产生了一个线程......

于 2013-05-22T10:36:03.863 回答