简体   繁体   中英

Do any methods have to be synchronized if there's only the main thread?

Do I really need to synchronize any methods if I'm not creating any threads (exception is the main). If so, can someone give a reason why and provide some examples please.

If you don't create any threads of your own, then no, you should not need to use the synchronized keyword. That's assuming you're not writing J2EE servlets or filters, or a library that others (who are using multiple threads) can call.

在这种情况下,您不需要任何同步,同步是多个线程访问共享数据时。

Synchronized methods are used when you don't want two threads to operate on any synchronized method at one time. If the application is single threaded there is no point taking a lock and adding an overhead of synchronization.

No, you should not as it will affect your performance. Synchronization should not be used if you are doing all in one thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM