Thijser
Thijser

Reputation: 2633

thread not running at the same time

I have created the following class for ant based pathfinding (I know horrible idea but still)...

public class main implements Runnable{
    static int[][] maze;
    static int[] targets;
    int treadnumber;
    public main(int i){
        treadnumber=i;
    }
    public static void main(String[] args){

        maze=mazeReader.read();
        colony.createscent(maze);   
        targets =targetReader.read();

        //number of running ants
        for (int i=0; i<4;i++){
            Thread a= new Thread(new main(i));
            a.run();
        }
        System.out.println("test");

        System.out.println("and the winner is:");
        System.out.println(colony.bestroute);
        System.out.println(colony.lengthbest/2);
    }

    public void run() {
        for (int i=0; i<100 ;i++){
            System.out.println(treadnumber);
        maze =mazeReader.read();
        ant a = new ant();
        a.loadmaze(maze.clone());
        a.start(targets.clone());
        }
    }


}

For effiency reasons this should run multi treaded however when I let them print the threadnumber I get a neat little ordended set of 100 0's followed by 100 1's ext. This whole code takes around 30 seconds to execute so they should run at least somewhat parallel. What am I doing wrong?

Upvotes: 2

Views: 143

Answers (2)

xagyg
xagyg

Reputation: 9721

At // number of running ants loop replace a.run(); with a.start();

Upvotes: 2

RamonBoza
RamonBoza

Reputation: 9038

Your problem is about invoking run method instead of starting thread.

Change

a.run();

to

a.start();

When you invoke run method, it executes the run without starting the thread process, without a scheduled call.

In order to lead the jvm to schedule your threads, you have to use start method.

Upvotes: 5

Related Questions