Tap and die will do it
The encoder is most commonly used, or more exactly the index marker on the encoder is what is used. This is nothing more or less than a switch that gets 'made' once per revolution of the spindle. Now an encoder is a neat way to do this, because it doesn't have bouncy contacts, and has a very short pulse duration, making a clean signal.
The rest of what happens are simple repetitive mechanical sequences. If motion of the Z axis motor begins with always the same delay from whenever the pulse was detected, then the carriage should track along the same path as before.
Analog circuits are good for detecting change of state. Digital detection of the encoder pulse can be more difficult because of sampling rate. An encoder running at 500 rpm, with a pulse width of only .001 revolution, requires a very high sampling rate to catch the pulse going past the detector. From my own testing with a Galil controller, I found that although the pulse could be detected with a high speed latch, there were other things going on within the controller that produced a variable length of time between detection and initiation of motor motion. This spoils the tracking of the tool and can easly spoil the thread at any time a next cut is attempted.
Lathe type threading does not require feedback because it is not 'rigid tapping'. The spindle never stops, so the Z axis cannot be electronically geared to mesh with the rotation of the spindle encoder because the sync will be lost whenever the Z must stop and reverse. A lathe spindle has far too much momentum to stop on a dime and reverse instantly unless it is a very powerful servo itself.