In both cases (fish and birds), the answer boils down to an impulse among every member of the group to maintain proper spacing with its neighbors combined with finely-tuned sense organs and quick reflexes. It once was thought that each group had a leader that somehow directed the movement of the entire group. We now believe that any individual in the group can initiate a sudden change of direction for the group. The animals next to it will respond accordingly to maintain proper spacing, and the ones next to them will follow suit, and so on, producing a ripple effect through the whole group. Each animal wants to stay close enough to others to maintain the safety of being in the group to begin with but far enough away to avoid collisions. These responses are so fast that to our eyes the whole movement seems synchronous.
Both schooling fish and flocking birds see and hear well and their eye placement facilitates visual detection of movement next to them. Fish have several added advantages: Sound travels faster underwater, they can smell one another, and they have a system of organs below the skin (the lateral line system) that senses changes in water pressure and thus movements of objects around them. Couple all these sensory stimuli with lightning-fast reflexes (some fish can accelerate to 20 body lengths/second in 1/50th of a second!) and you get a group numbering in the thousands behaving as if it were a single animal.