A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© shuimu_88 中级黑马   /  2014-7-18 00:36  /  736 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

各位大牛好,我运行了一个小程序,编译没问题,但是就是没有打印结果,不知道问题出在哪里,
请各位指教,十分感谢!!!


/*通过设置线程不同的优先级,观察各个线程运行的先后顺序,
不同优先级的线程占用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);
               
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马