ThreadUtil使API更加具体化,因而为线程编程新手提供了一定的方便性,从而简化了API。其源码如下:
[java]
package mybole;
public class ThreadUtil {
public static ThreadGroup getSystemThreadGroup()
{
ThreadGroup systemThreadGroup;
ThreadGroup parentThreadGroup;
systemThreadGroup = Thread.currentThread().getThreadGroup();
while((parentThreadGroup = systemThreadGroup.getParent()) != null)
systemThreadGroup = parentThreadGroup;
return systemThreadGroup;
}
public static void printSystemThreadGroup()
{
System.out.println(getSystemThreadGroup());
}
public static Thread getThread()
{
return new Thread(new Job());
}
public static Thread[] getThreads(int n)
{
Thread[] ta = new Thread[n];
for(int i=0; i
ta[i] = getThread();
ta[i].start();
}
return ta;
}
public static ThreadGroup[] getThreadGroup()
{
ThreadGroup stg = getSystemThreadGroup();
int nog = stg.activeGroupCount()+1;
ThreadGroup[] tga = new ThreadGroup[nog];
stg.enumerate(tga);
tga[tga.length - 1] = stg;
return tga;
}
public static void print(Object[] o)
{
for(Object x:o)
System.out.println(x);
}
public static void print(Thread[] o)
{
for(Thread x:o)
System.out.println(x+" isAlive="+x.isAlive()+" name="+x.getName()+" isDaemon="+x.isDaemon());
}
public static Thread[] getThreads()
{
ThreadGroup stg = getSystemThreadGroup();
Thread[] ta = new Thread[stg.activeCount()];
stg.enumerate(ta, true);
}
public static void setPriority(Thread[] ta, int p)
{
for(Thread x:ta)
x.setPriority(p);
}
public static void setName(Thread[] ta, String n)
{
for(Thread x:ta)
x.setName(n);
}
public static void main(String[] args)
{
System.out.println("Hello Thread!!");
Thread[] ta = getThreads();
//***************注释*****************
//Thread[] ta = getThreads(3);
print(ta);
setPriority(ta, 10);
setName(ta, "blueln");
print(ta);
}
}
[java]
package mybole;
public class Job implements Runnable
{
static int totalNumberOfJobs = 0;
int jobNumber = 0;
Job()
{
jobNumber = totalNumberOfJobs;
totalNumberOfJobs++;
}
public void run()
{
while(true)
{
System.out.println("t#="+jobNumber+"\t" + new java.util.Date());
try
{
Thread.sleep((int)(Math.random()*10000));
}
catch(InterruptedException e)
{
e.getMessage();
}
}
}
}
输出结果:
[java]
Hello Thread!!
Thread[Reference Handler,10,system] isAlive=true name=Reference Handler isDaemon=true
Thread[Finalizer,8,system] isAlive=true name=Finalizer isDaemon=true
Thread[Signal Dispatcher,9,system] isAlive=true name=Signal Dispatcher isDaemon=true
Thread[Attach Listener,5,system] isAlive=true name=Attach Listener isDaemon=true
Thread[main,5,main] isAlive=true na