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) slowly changing and b) drops below some low threshhold, then throw the big switch. 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. 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. 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 very long time of coordinated tweaking to be able to connect them together again.