Java 线程屈服/饥饿问题

标签 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++;
    }

    }

然后这是 Jumbler 运行方法:

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

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

最佳答案

我认为问题出在主循环中的 transactions[copy].run(); 中。这个直接调用 run 方法,而不是在另一个系统线程中。而是使用 transactions[copy].start(); 启动线程。

关于Java 线程屈服/饥饿问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5844175/

相关文章:

java - Android SDK 通过HTTP get获取图片

java - hibernate 嵌套条件为空结果

java - LinkedBlockingQueue 中 put() 的性能

c - Windows在默认线程池中设置最大线程数

ruby - `Thread.current.object_id` 可以在线程本身内部更改吗?

c# - 实现线程安全的队列或列表时,返回Count前是否需要加锁?

java - Java 中的元组(异构元素的不可修改有序列表)支持

java - 递归编写find方法,LinkedList

java - 如何操作 JavaFX 应用程序中的所有 Activity 线程

C++ 线程安全和 notify_all()