Before connecting a generator to the grid, they spin it up to more or less the right speed. Then they hook what is basically a voltmeter between a generator phase, and the corresponding line phase. They adjust the generator drive until the observed voltage is
a) very slowly changing (frequency difference below some threshold) and
b) drops below some low voltage threshold (phase difference close enough so the power flow that results when they throw the big switch is manageable).
Once the generator is connected to the grid, it always stays in phase. If not driven mechanically, it will act as a motor. The amount of power it draws from or exports to the grid is controlled by how hard it is driven mechanically.
Each generator is connected to its local part of the grid, synced to its local frequency. There will be a slight phase difference between the generator and the local grid.
Where two separately controlled grids are If the generator is supplying power to the grid, its phase will be connectedslightly in advance. The larger the power input to the generator, say by the Anglo-French undersea cablelarger the phase difference, it is done with DC. It is easy atand the receiving endlarger will be the power exported to synchronise the invertersgrid.
This 'power flow follows phase difference' extends to whole areas of the grid. If there is a large load in the south, the generators in the south will slow down initially, retarding their phase with respect to the north. This phase difference will create a power flow from north to south.
Where you have a nationwide grid, the management strive very hard never to let any significant part become 'islanded' from the other part. Once they drift apart in phase, it may take a long time before they can be brought together again, as the phase matching will need to be exquisitely accurate to avoid a huge power flow at the time of connection.
Where two separately controlled grids are to be connected, say by the Anglo-French undersea cable, it is done with DC. It is easy at the receiving end to synchronise the inverters to the grid.
Keeping the grid in phase with an average of 50 cycles per second over the course of a day, is simply done by feeding in more or less power, to speed or slow the grid frequency respectively, usually at night when there's a bit more slack in the demand.