java中的多线程

时间:2012-12-19 09:36:59

标签: java multithreading

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

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);
     }
}

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

2 个答案:

答案 0 :(得分: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.
            }
        }
    );
}

答案 1 :(得分: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");