running multiple command in same line

I have 5 hosts and each host as 3 java process .I have one machine which has ssh keys so it can login without any passwords etc to all the machines.

How can I find out say jstack or some command so it goes to each machine and run the command . For example machine 1 has 3 java process and they all have different process ids . I want to run " jstack <pid> " on all machines .

I tried something like

for i in 1 2 3 ; do echo "running jstack"; ssh -q host1 pgrep java ; echo ""; done

I can get the process for each machine but not sure how to run "jstack pid> based on pid

thanks in advance
Joe

#!/bin/bash
for i in {1..3}
do 
    echo "running jstack"
    ssh -q host$i "jstack $(pgrep java)"
done

"jstack $(pgrep java)" didnt work. It doesnt seem like it is returning the variables