gpt4 book ai didi

java - java中原始整数值的同步

转载 作者:行者123 更新时间:2023-11-30 08:12:00 26 4
gpt4 key购买 nike

我有两个java线程。其中一个打印偶数,另一个打印奇数。我需要按自然顺序打印数字。是否可以将两个线程同步为仅使用原始整数,如下所示?Node:原始赋值在 java 中跨 jvm 是原子的。

public class NaturalNumber{

volatile int ai = 0;
public static void main(String str[]){
final NaturalNumber nn = new NaturalNumber();

Thread even = new Thread(new Runnable(){
int i=0;
public void run(){
//int i=0;
while(i<=200){
if(nn.ai ==0){
System.out.println(i);
i=i+2;
nn.ai =1 ;

}
}
}
});

Thread odd = new Thread( new Runnable(){
int i=1;
public void run(){
//int i=1;
while(i<=200){
if(nn.ai ==1) {
System.out.println(i);
i=i+2;
nn.ai =0 ;
}
}
}
});


odd.start();
even.start();


}

}

最佳答案

这是使用锁定和同步来实现它的方法,我认为这不太容易出错。

public class NaturalNumber{

private boolean printEven = true;
private Object lock = new Object();

public NaturalNumber()
{
new Thread(()->even()).start();
new Thread(()->odd()).start();
}

private void even()
{
int i = 0;
while(i<=200)
{
synchronized (lock)
{
if(printEven)
{
System.out.println(i);
i += 2;
lock.notify();
printEven = false;
}
else //flag says next odd is to be printed, so wait until it has
{
try
{
lock.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
private void odd()
{
int i = 1;
while(i<=200)
{
synchronized (lock)
{
if(!printEven)
{
System.out.println(i);
i += 2;
lock.notify();
printEven = true;
}
else //flag says next even is to be printed, so wait until it has
{
try
{
lock.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}

public static void main(String str[]){

new NaturalNumber();
}
}

关于java - java中原始整数值的同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30262614/

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