代码之家  ›  专栏  ›  技术社区  ›  Azodious

逻辑:程序未终止

  •  0
  • Azodious  · 技术社区  · 4 年前

    我写了一个小程序来交替打印奇偶数,但有一个问题:

    因为线程应该在 await

    public class Worker implements Runnable
    {
        private ReentrantLock rLock = null;
        private Condition condition = null;
        private String name;
        volatile static boolean isEvenTurn = true;
        
        public Worker(String name, ReentrantLock rLock, Condition condition)
        {
            this.name = name;
            this.rLock = rLock;
            this.condition = condition;
        }
        
        @Override
        public void run() 
        {
            try
            {
                if(name.equals("ODD"))
                    printOdd();
                else
                    printEven();
            }
            catch(Exception e) { e.printStackTrace();}
            
        }
        
        private void printOdd() throws Exception
        {
            while(isEvenTurn);
            for(int i=1;i<10;i+=2)
            {
                try
                {
                    rLock.lock();
                    System.out.println(i);
                }
                catch(Exception e) {e.printStackTrace();}
                finally
                {
                    condition.signal();
                    condition.await();
                    rLock.unlock();
                }
            }
        }
        
        private void printEven() throws Exception
        {
            for(int i=0;i<10;i+=2)
            {
                try
                {
                    rLock.lock();
                    System.out.println(i);
                    isEvenTurn = false;
                }
                catch(Exception e) {e.printStackTrace();}
                finally
                {
                    condition.signal();
                    condition.await();
                    rLock.unlock();
                }
            }
        }
        
        public static void main(String[] args) 
        {
            ReentrantLock rLock = new ReentrantLock();
            ExecutorService service = Executors.newFixedThreadPool(2);
            
            Condition c = rLock.newCondition();
            Worker oddPrinter = new Worker("ODD",rLock,c);
            Worker evenPrinter = new Worker("EVEN",rLock,c);
            
            service.execute(evenPrinter);
            service.execute(oddPrinter);
            
            service.shutdown();
        }
    }
    
    1 回复  |  直到 4 年前
        1
  •  2
  •   Vaibhav_sorathiya    4 年前

    在print偶数()方法中添加以下行:在finally块中:

           finally
            {
                condition.signal();
                if(i < 10)condition.await(); 
                rLock.unlock();
            }
    

    通过添加此条件,当 i=10您的线程将不再等待。