I can't say for certain what causes this to happen.
You have to understand a little bit how the lock bone feature works. It uses what is called an "IK solver". It uses an algorithm to determine how each bone will reach a "solution".
Each bone is constrained by it's location, length and connection to the other bones in the chain. When you lock any bone in that chain each bone must now use this IK solving algorithm to determine the rotation it needs to use to reach that goal. This isn't always a perfect or expected solution. It is math. It may cause bones to spin or behave strangely if the bones are in a position that makes it impossible to reach the "goal" in the way you expect.
If you have a lot of bone rotated into an awkward, tight positions, and then you lock a bone at the end, it could create a situation that the IK solver just can't resolve without spinning bones into odd rotations.
I can't tell from your images what is causing this spinning and rotation. If I could look at the actual file I might be able to tell you what is going on and how to fix it. I tried to duplicate this on my own using the images as a guide but I can't make the bones spin around the way you describe. Bone locking works fine for my sample. So I need to see your file to help you.