Java线程产生/饥饿问题

0 java multithreading thread-safety

我正在编写一个运行多线程银行的代码.我首先用一个程序创建一个线程数组,然后将它们传递给另一个运行循环的线程来启动它们.对于应用程序的一部分,我有一个CPU密集型方法,基本上在一个彼此之间运行一系列循环.唯一的问题是,由于某种原因,它没有产生我认为应该的方式.以下是运行线程的代码:

public void run(){
    this.setPriority(MAX_PRIORITY);
    int count = 0;

    while(count<transactions.length){
        int copy = count;
            if(transactions[copy] instanceof Jumbler){
                System.out.println(copy + " is a jumbler.");
            }
            else{
                System.out.println(copy  + " is not a jumbler");
            }
        transactions[copy].run();
        count++;
    }

    }
Run Code Online (Sandbox Code Playgroud)

然后是Jumbler run方法:

    public void run(){
    System.out.println("running jumbler");
    Thread.yield();
    Thread.currentThread().yield();
    try{
        Thread.currentThread().sleep(5000);
    }catch(InterruptedException e){}
    //this.setPriority(MIN_PRIORITY);
    System.out.println("still running.");
    Thread.yield();
    nums = new int[1000];
    int i = 0;

    do{
        Thread.yield();

        for(int x=0;x<1000;x++){
            Thread.yield();
            //System.out.println("in the loop");
            nums[x]=(int)(Math.random()*10000)+1;
            for(int y = 0;y<1000;y++){
                Thread.yield();
                //System.out.println("in the the loop");
                for(int z = 0;z<100;z++){
                    Thread.yield();
                }
            }
        }
        Thread.yield();
        i++;
        System.out.println(whichJumble + ": " + i);
    }while(i<1000);
}
Run Code Online (Sandbox Code Playgroud)

所以,问题是我希望它产生,允许main方法继续运行更多线程,但它阻塞并等待Jumbler完成(这需要很长时间).知道为什么会发生这种情况或如何解决它?

How*_*ard 6

我想transactions[copy].run();你的主循环中会出现问题.这个直接调用run方法而不是另一个系统线程.而是启动线程transactions[copy].start();.