A Thai judge shot himself in a courtroom after delivering a rare speech railing against the country's justice system.

Kanakorn Pianchana acquitted five Muslim men of murder on Friday before calling for a fairer judiciary.

He then recited a legal oath, pulled out a pistol and shot himself in the chest.

But the judge survived and was rushed to hospital where he is recovering from his injuries.

A statement believed to have been written by the judge before giving his ruling suggests that his suicide attempt could have been related to alleged interference in the case.

What happened in court?

The judge worked at the Yala court in the insurgency-hit south of Thailand.

After acquitting the five men of murder and firearms offences, he addressed the court with an impassioned speech that he broadcast live on Facebook.

"You need clear and credible evidence to punish someone. So if you're not sure, don't punish them," he said.

"I'm not saying that the five defendants didn't commit the crimes, they might have done so," he added.

"But the judicial process needs to be transparent and credible... punishing the wrong people makes them scapegoats."

The Facebook feed then cut but people in court said the judge read out a legal oath in front of the former Thai king's portrait before whipping out a pistol and shooting himself.

He was rushed to hospital where he is reported to be in a stable condition.

Why did he do it?

It is not fully clear why Judge Pianchana attempted to take his own life.

Suriyan Hongvilai, the spokesman of the Office of the Judiciary, told the AFP news agency he shot himself due to "personal stress".

But local media reported that the judge could have been referring to the case he had just ruled on.

A statement believed to have been written by the judge and posted to Facebook before he shot himself stated that he had been pressured to find the men guilty despite lack of evidence.

"At this moment, other fellow judges in Courts of First Instance across the country are being treated the same way as I was," he wrote.

"[If] I cannot keep my oath of office, I'd rather die than live without honour."

Criticism of the judicial system by judges is extremely rare in Thailand.

Rights groups have alleged that security forces trump up charges against Muslim suspects in the Malay-Muslim majority region.