-2

我有一个循环,但它太重了,所以我想在多个线程中共享相同的内容,但我不知道该怎么做。

while(!labyrinth.exit(bob3) && !labyrinth.exit(bob2)) {

     Collection<Room> accessibleRooms = labyrinth.accessibleRooms(bob3);

     if (bob3.canMove()) {
         destination = bob3.makeChoice(accessibleRooms);
     }

     if (destination != bob3.getPosition()) {
         destination.receive(bob3);
     }

     accessibleRooms = labyrinth.accessibleRooms(bob2);   

     if (bob2.canMove()) {
         destination = bob2.makeChoice(accessibleRooms);
     }

     if (destination != bob2.getPosition()) {
         destination.receive(bob2);
     }
}

如您所见,在这个循环中,我们有两个相同的操作,因此可以让每个操作使用不同的线程。

4

2 回答 2

4

制作“多线程”的最简单方法:

while(....){
    new Thread(new Runnable(){
            public void run(){
               // put your code here.
            }
        }
    ).start();
}

不要忘记让你的变量最终

编辑:你想要它:)

ExecutorService exec= Executors.newCachedThreadPool()
while(....){
    exec.execute(new Runnable(){
            public void run(){
               // put your code here.
            }
        }
    );
}
于 2012-12-19T09:42:10.203 回答
1
    final CyclicBarrier c = new CyclicBarrier(2);

    Runnable r1 = new Runnable()
    {

        @Override
        public void run()
        {
            while ( !labyrinthe.sortir(bob3) )
            {

                Collection<Salle> sallesAccessibles = labyrinthe.sallesAccessibles(bob3);
                if ( bob3.peutSeDeplacer() )
                    destination = bob3.faitSonChoix(sallesAccessibles); // on demande au heros de faire son choix de salle
                if ( destination != bob3.getPosition() )
                    destination.recevoir(bob3); // deplacement
            }
            try
            {
                c.await();
            }
            catch ( InterruptedException e )
            {
                ;
            }
            catch ( BrokenBarrierException e )
            {
                ;
            }
        }
    };

    Runnable r2 = new Runnable()
    {
        @Override
        public void run()
        {
            while ( !labyrinthe.sortir(bob2) )
            {
                Collection<Salle> sallesAccessibles = labyrinthe.sallesAccessibles(bob2);
                if ( bob2.peutSeDeplacer() )
                    destination = bob2.faitSonChoix(sallesAccessibles); // on demande au heros de faire son choix de salle
                if ( destination != bob2.getPosition() )
                    destination.recevoir(bob2); // deplacement

            }
            try
            {
                c.await();
            }
            catch ( InterruptedException e )
            {
                ;
            }
            catch ( BrokenBarrierException e )
            {
                ;
            }
        }
    };

    Thread t1 = new Thread(r1);
    Thread t2 = new Thread(r2);

    t1.start();
    t2.start();

    c.await();

    System.out.println("Done");
于 2012-12-19T09:48:10.053 回答