Underlying cellular networks, device-to-device (D2D) communications are a practical network technology that can increase power efficiency and spectrum usage for close-proximity wireless services and applications. However, D2D link interference, when sharing resources with cellular users (CUs), poses a major challenge in such distribution situations. In this research, we primarily utilize wireless channel data that exhibits slowly shifting large-scale fading to conduct spectrum sharing and power allocation. The overall ergodic capacity of all cellular user equipment (CUE) links is initially considered as the optimization target in order to maximize the overall throughput of CUE links while ensuring the reliability of each D2D link. Then, the expansion of the minimum ergodic capacity is measured to ensure a more consistent capacity performance across all CUE links. We utilized algorithms that are resilient to channel fluctuations and produce optimal resource allocation. We use MATLAB, and the computer simulation validates its intended performance.