Getting the priority
public class SimplePriorities extends Thread
{
private int countDown = 5;
private volatile double d = 0;
public SimplePriorities(int priority)
{
setPriority(priority);
start();
}
public String toString()
{
return super.toString() + ": " + countDown;
}
public void run()
{
while(true)
{
for(int i = 1; i < 100000; i++)
d = d + (Math.PI + Math.E) / (double)i;
System.out.println(this);
if(--countDown == 0) return;
}
}
public static void main(String[] args)
{
new SimplePriorities(Thread.max_priority);
for(int i = 0; i < 5; i++)
new SimplePriorities(Thread.min_priority);
}
}
Monitoring
a Thread
class MyThread extends Thread
{
boolean waiting= true;
boolean ready= false;
MyThread(){}
public void run()
{
String thrdName = Thread.currentThread().getName();
System.out.println(thrdName + " starting.");
while(waiting)
System.out.println("waiting:"+waiting);
System.out.println("waiting...");
startWait();
try
{
Thread.sleep(1000);
}
catch(Exception exc)
{
System.out.println(thrdName + " interrupted.");
}
System.out.println(thrdName + " terminating.");
}
synchronized void startWait()
{
try
{
while(!ready) wait();
}
catch(InterruptedException exc)
{
System.out.println("wait() interrupted");
}
}
synchronized void notice()
{
ready = true;
notify();
}
}
public class Main
{
public static void main(String args[])throws Exception
{
MyThread thrd = new MyThread();
thrd.setName("MyThread #1");
showThreadStatus(thrd);
thrd.start();
Thread.sleep(50);
showThreadStatus(thrd);
thrd.waiting = false;
Thread.sleep(50);
showThreadStatus(thrd);
thrd.notice();
Thread.sleep(50);
showThreadStatus(thrd);
while(thrd.isAlive())
System.out.println("alive");
showThreadStatus(thrd);
}
static void showThreadStatus(Thread thrd)
{
System.out.println(thrd.getName()+"
Alive:="+thrd.isAlive()+"
State:=" + thrd.getState() );
}
}
Getting Thread Name
public class TwoThreadGetName extends Thread
{
public void run()
{
for (int i = 0; i < 10; i++)
{
printMsg();
}
}
public void printMsg()
{
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
}
public static void main(String[] args)
{
TwoThreadGetName tt = new TwoThreadGetName();
tt.start();
for (int i = 0; i < 10; i++)
{
tt.printMsg();
}
}
}
No comments:
Post a Comment