How do you prevent race conditions and ensure thread safety in a multi-threaded application where multiple transactions might occur simultaneously?