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

时间:2018-11-01 17:12:46

标签: java

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

您只能使用sleep,interrupt,volatile和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();
      }
    }
  }
}

2 个答案:

答案 0 :(得分:1)

您需要顶部再使用一个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;
  }
 }
}

答案 1 :(得分:0)

这使用单个accept字段来保存值。当该值为node时,可以发布一个新值;当该值为负值时,它将充当毒药,从而停止打印线程。

volatile