李海成 2019-04-04 11:46 采纳率: 0%
浏览 263

如何将两个线程绑定到同一个cpu? Java-Thread-Affinity能否实现?

1.需求,现在需要将两个线程绑定到同一个cpu运行。
2.进度,现在查到 Java-Thread-Affinity工具是最接近这种需求的,但是感觉 Java-Thread-Affinity只能让某个线程独占cpu,。所以, Java-Thread-Affinity能实现这种需求吗?
3.代码

/*
 * Copyright 2016 higherfrequencytrading.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package net.openhft.affinity;

import static net.openhft.affinity.AffinityStrategies.*;

/**
 * @author peter.lawrey
 */
public final class AffinityLockBindMain {
    private AffinityLockBindMain() {
        throw new InstantiationError("Must not instantiate this class");
    }

    public static void main(String... args) throws InterruptedException {
        AffinityLock al = AffinityLock.acquireLock();
        try {
            // find a cpu on a different socket, otherwise a different core.
            System.out.println("al id " + al.cpuId());
            AffinityLock readerLock = al.acquireLock(SAME_CORE, SAME_SOCKET);
            System.out.println("reader id " + readerLock.cpuId());
            new Thread(new SleepRunnable(readerLock, true), "reader").start();

            // find a cpu on the same core, or the same socket, or any free cpu.
            //AffinityLock writerLock = al.acquireLock(SAME_CORE, SAME_SOCKET);
            System.out.println("writerLock id " + readerLock.cpuId());
            new Thread(new SleepRunnable(readerLock, true), "writer").start();

            Thread.sleep(200);
        } finally {
            al.release();
        }

        // allocate a whole core to the engine so it doesn't have to compete for resources.
        al = AffinityLock.acquireCore(false);
        System.out.println("engine id " + al.cpuId());
        new Thread(new SleepRunnable(al, true), "engine").start();

        Thread.sleep(200);
        System.out.println("\nThe assignment of CPUs is\n" + AffinityLock.dumpLocks());
    }

    static class SleepRunnable implements Runnable {
        private final AffinityLock affinityLock;
        private final boolean wholeCore;

        SleepRunnable(AffinityLock affinityLock, boolean wholeCore) {
            this.affinityLock = affinityLock;
            this.wholeCore = wholeCore;
        }

        public void run() {
            affinityLock.bind(wholeCore);
            try {
                Thread.sleep(1000);
                Thread t = Thread.currentThread();
                String name = t.getName();
                System.out.println("name=" + name);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                affinityLock.release();
            }
        }
    }
}

4.报错
Exception in thread "writer" java.lang.IllegalStateException: cpu 6 already bound to Thread[reader,5,main]
at net.openhft.affinity.AffinityLock.bind(AffinityLock.java:240)
at net.openhft.affinity.AffinityLockBindMain$SleepRunnable.run(AffinityLockBindMain.java:68)
at java.lang.Thread.run(Thread.java:748)

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-08 18:23
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    Java中的Thread#setPriority(int)方法可以用来设置线程优先级。然而,这个方法只能在当前线程中使用,并且不能改变一个已存在的线程的优先级。

    如果你想让两个线程都绑定到同一个CPU,你可以尝试以下几种方法:

    1. 使用Thread.setDaemon(boolean)方法来设置线程为守护线程(daemon线程),这样它们会自动在主线程退出后继续执行。
    2. 将两个线程合并成一个线程池并启动它。
    3. 在每个线程开始时调用Thread.setPriority(int)方法来设置优先级。

    例如,如果你有一个名为MyThread的类,你可以在其构造函数中添加以下内容:

    public MyThread(int priority) {
        super();
        setPriority(priority);
    }
    

    然后你在主方法中创建这两个线程:

    new Thread(new MyThread(1)).start();
    new Thread(new MyThread(2)).start();
    

    或者

    ExecutorService executor = Executors.newFixedThreadPool(2);
    
    executor.execute(new MyThread(1));
    executor.execute(new MyThread(2));
    

    注意:这些方法可能不会立即生效,因为它们可能会被其他线程或进程阻塞。为了确保它们正确工作,你需要等待所有任务完成后再进行检查。

    评论

报告相同问题?