stevejobsfan0123's note is one reason for such popups appearing in Safari. If that is the case, you haven't been hacked by anyone or anything.
To fully explain how these popups work on the Mac (and Windows):
1) You hit a bad web site and the scary sounding popup appears.
2) You click OK or whatever button is there to try and dismiss it. The popup seems to be unresponsive, or comes back after a very brief time off the screen.
3) This happens because of a JavaScript action they're using. JavaScript (no relation at all to Java) is used extensively on the web. Much of what we take for granted wouldn't work if you turned it off in a web browser's preferences. Like the buttons across the top of this page. Anything on a page that changes when you move your mouse over or across it is JavaScript in action. In this case, the mouseover command.
4) What these scammers use is another JavaScript action to "do on exit". In the case of these popups, you really are closing it when you click the button, but the final HTML command of the popup is a JavaScript "do on exit". And the "what to do" is to display the same popup.
5) Safari, and pretty much all web browsers force you to attend to the button on a popup before it will let you do anything else. Which is why you can't get to the preferences or other tabs. So there you are, stuck in a loop of closing the popup, only to have it immediately display again. The crooks are using a simple built-in function of all web browsers to make your web browser appear to be stuck. No malware of any kind is necessary to accomplish this. Just a browser with JavaScript enabled. And it pretty much has to be on in order to use virtually any web site.
The general fix is to Force Quit Safari, then hold down the Shift key and relaunch it. Holding the Shift key tells Safari not to load any of the web sites from the previous session.
If that alone doesn't do it, the other possibility is that you installed adware along with something else. Most adware is simply annoying. They display tons of ads whenever you're using your browser. Recently though, some nastier adware has also been causing similar threat popups to appear. They are again harmless on their own, but won't go away until you remove the adware that's causing them to appear.
You can either follow Apple's manual instructions for removing adware, or use the free automated tool, AdwareMedic.
It should be noted that Apple's manual removal instructions are typically outdated. Sometimes a lot outdated. It depends on when Apple last updated their instructions page. If you would prefer to manually remove the adware on your system, you can find much more up-to-date instructions on The Safe Mac's adware removal page.