The parallels between the crucifixion and Psalm 22 are too precise and too numerous to dismiss. The Holy Spirit, through the Father's omniscient view, saw the future crucifixion and gave David the vision and inspiration to report it 1,000 years before it would occur.
Either Jesus was clear in mind and consciously pointing back to David's psalm as prophetic...
...or at the moment it did occur, Jesus was delirious and just happened to cry out the very words that the Holy Spirit had given to David 1,000 years earlier.
I think the former is more likely true, inasmuch as that declaration was not Jesus' final words. He continued to speak coherently afterward, clearly not delirious.
And, of course, Jesus would have been quite familiar with the Psalm. He already knew all the scriptures that pointed to Him. He would know that psalm, in particular, prophesied his manner of death.