各位大牛好,我运行了一个小程序,编译没问题,但是就是没有打印结果,不知道问题出在哪里,
请各位指教,十分感谢!!!
/*通过设置线程不同的优先级,观察各个线程运行的先后顺序,
不同优先级的线程占用CPU的时间。虽然优先级低的线程先启动,
但仍然是高的先得到控制权而执行*/
class PriorityTime implements Runnable
{
int counter=0;
private boolean flag=true;
Thread t;
public PriorityTime(int p)
{
t=new Thread(this);
t.setPriority(p);
}
public void run()
{
while(flag)
{
counter++;
}
}
public void stop()
{
flag=false;//终止线程
}
public void start()
{
t.start();
}
}
class CreateTwoThread
{
public static void main(String[] args)
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
PriorityTime higher=new PriorityTime(Thread.NORM_PRIORITY+2);
PriorityTime lower=new PriorityTime(Thread.NORM_PRIORITY-2);
lower.start();
higher.start();
try
{
Thread.sleep(7000);
}
catch (Exception e)
{
System.out.println("Main thread interrupted");
}
lower.stop();
higher.stop();
try
{
higher.t.join();//?
lower.t.join();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Low-priority thread:"+lower.counter);
System.out.println("higher-priority thread:"+higher.counter);
}
}
|
|