gpt4 book ai didi

java - Java 8 的线程排序

转载 作者:行者123 更新时间:2023-11-29 04:29:30 24 4
gpt4 key购买 nike

我有一个简单的程序,可以让两个线程交替打印增量数字。

所以,第一个线程打印:1

第二线程打印:2

第一个线程打印:3...等等

我可以使用“线程”类来执行此操作。但我想看看如何使用 Executor 类来执行此操作。

使用以下代码....执行程序类似乎不起作用。任何指针??

代码:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LocksPackagePractice {

private int i = 0;

ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();

Runnable r = () -> {
for(int x = 0; x < 5; x++){
printValue();
}
printValue();
};

public static void main(String[] args) {

new LocksPackagePractice().trigger();
}

void trigger(){
ExecutorService service = Executors.newFixedThreadPool(2);
service.execute(r);
}

void printValue(){

lock.lock();

try {

i++;
System.out.println(Thread.currentThread().getName() + " and value is = " + i);

condition.signal();
condition.await();

} catch(InterruptedException e){
e.printStackTrace();
}finally {
lock.unlock();
}

}
}

最佳答案

对您的程序进行了一些更改。运行它并检查它是否解决了困惑。

public class LocksPackagePractice {
private int i = 0;
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
Runnable r = () -> {
printValue();
};
public static void main(String[] args) {
new LocksPackagePractice().trigger();
}
void trigger() {
ExecutorService service = Executors.newFixedThreadPool(2);
service.submit(r);
for (int i = 0; i < 5; i++) {
service.execute(r);
}
}
void printValue() {
lock.lock();
try {
i++;
System.out.println(Thread.currentThread().getName() + " and value is = " + i);
condition.signal();
condition.await();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}

这将为您提供以下输出

pool-1-thread-1 and value is = 1
pool-1-thread-2 and value is = 2
pool-1-thread-1 and value is = 3
pool-1-thread-2 and value is = 4
pool-1-thread-1 and value is = 5
pool-1-thread-2 and value is = 6

关于java - Java 8 的线程排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44383718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com