gpt4 book ai didi

java - 如何打印斐波那契数列,多线程?

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

任务是编写一个程序,创建并启动两个线程 ThreadFibonacci 和 ThreadOutput。 ThreadFiobnacci 应该计算斐波那契数并将结果放入其静态公共(public)变量中。 ThreadOutput 应输出斐波那契数,并且 ThreadOutput 必须是守护线程。您必须让线程只写出每个斐波那契数一次。我不知道如何完成任务的最后一部分。

只能使用 sleep、interrupt、volatility 和 join。

这是我尝试过的:

import java.util.Scanner;

public class Zadatak2{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = reader.nextInt();

Thread threadFibonaci = new Thread(new ThreadFibonaci(n));
Thread threadOutput = new ThreadOutput();

threadFibonaci.start();
threadOutput.start();

}
}

class ThreadFibonaci implements Runnable{

public static volatile long fn;
private int n;

public ThreadFibonaci(int n){
this.n = n;
}

public void run(){
long f0 = 0;
fn = f0;
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
long f1 = 1;
fn = f1;
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
for(int i=0; i<n; i++){
fn = f0 + f1;
f0 = f1;
f1 = fn;
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
}
}

class ThreadOutput extends Thread{

public ThreadOutput(){
setDaemon(true);
}

public void run(){
while(true){
System.out.println(ThreadFibonaci.fn);
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
}
}

最佳答案

您需要再使用一个 volatile 变量来存储当前数字是否已打印的标志

class ThreadFibonaci implements Runnable{

public static volatile long fn;
public static volatile boolean printed = false;
private int n;

public ThreadFibonaci(int n){
this.n = n;
}

public void run(){
long f0 = 0;
fn = f0;
while (!printed) {
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
long f1 = 1;
fn = f1;
printed = false;
while (!printed) {
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
for(int i=0; i<n; i++){
fn = f0 + f1;
f0 = f1;
f1 = fn;
printed = false;
while (!printed) {
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}

class ThreadOutput extends Thread{

public ThreadOutput(){
setDaemon(true);
}

public void run(){
while(true){
while (ThreadFibonaci.printed) {
try{
Thread.sleep(500);
}catch(Exception e){
e.printStackTrace();
}
}
System.out.println(ThreadFibonaci.fn);
ThreadFibonaci.printed = true;
}
}
}

关于java - 如何打印斐波那契数列,多线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53106118/

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