半吊子的程序狗 2020-10-13 10:49 采纳率: 0%
浏览 56
已采纳

新手請教:main方法調用自身的類不會死循環嗎?

剛學java,特別不明白的地方想請教大家

SpringApplication.run(applicationStart.class,args);
這個run方法將applicationStart類當做參數傳入,自己老是覺得會是一個死循環,但實際又并不會發生死循環,不明白這其中的機制是怎樣的。

图片说明

參考回復和其他的一些文章,寫了一個例子,找到可以導致死循環的地方。

cOberser

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test1
{
    public class cOberser
    {

        public cSubject mySubject;
        public string strName;
        public cOberser(cSubject pcs, string obname)
        {
            this.mySubject = pcs;
            this.strName = obname;

        }
        public void update()
        {
            mySubject.notifyAllObservers();//這裡可以導致死循環
            Console.WriteLine("update");
        }
    }
}

cSubject

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test1
{
  public  class cSubject
    {
        public  List<cOberser> listbservers= new List<cOberser>();

        private int state;

        public int getState()
        {
            return state;
        }

        public void setState(int state)
        {
            this.state = state;
            notifyAllObservers();
        }

        public void attach(cOberser observer)
        {
            this.listbservers.Add(observer);
        }

        public void notifyAllObservers()
        {

            foreach (cOberser observer in listbservers)
            {
                Console.WriteLine(observer.strName);
                observer.update();
            }

        }


        public void f1()
        {
            Console.WriteLine("f1");
        }
    }
}

Main

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test1
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("開始進入main");

            cSubject cs1 = new cSubject();

            cs1.attach(new cOberser(cs1,"zhangsan"));
            cs1.attach(new cOberser(cs1, "lis4"));
            cs1.notifyAllObservers();



            Console.ReadKey();

        }


    }
}

  • 写回答

2条回答 默认 最新

  • threenewbee 2020-10-13 19:35
    关注

    这里传入类名,并不是直接调用,会不会无限递归,取决于它调用的是什么方法,显然不是main方法。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?