尽可能减少同步代码块的数量和长度。
同步方法或同步代码块?
在有必要进行同步的场合下,应该尽量缩小同步代码块。
In cases where synchronization is necessary, the synchronized code block should be minimized.
创建同步代码块产生了16行的字节码,而创建同步方法仅产生了5行。
Creating the synchronized block yielded 16 lines of bytecode, whereas synchronizing the method returned just 5.
同步代码块所需的执行时间越长,其他线程等待进入该代码块的时间就越长。
The longer a synchronized code block requires for execution, the longer other threads wait to enter that block.
如果同步代码块不够小,应该对代码进行分析,对其重构,以使所有可以异步运行的代码均位于同步代码块之外。
If it is not small enough, you should analyze your code and refactor it in such a way that anything that could run asynchronously is located outside of the synchronized block.
只有方法和代码块能被同步标记。
根据我们的观察,我们似乎需要对一些锁的访问进行优化,比如线程执行的同步块代码在一个循环体中。
In light of our observation it seems as if we should be able to optimize access in the case where a thread is looping over a synchronized block of code.
同步的代码块在执行之前需要与客户类对象相关的锁。
This synchronized code block acquires the lock associated with the customer class object before it executes.
更糟糕的还在后面;在合并锁之后,同步的代码块中只包含一个递增序列,因而可以降低强度,转换成一个单独的相加。
And it gets worse; after coalescing the locks, the synchronized body will contain only a sequence of increments, which can be strength-reduced into a single addition.
能够进行同步访问的代码块有时称为关键部分。
Code areas with synchronized access are sometimes called critical sections.
同步语句一次仅允许一个线程进入代码块。
The synchronized statement enbales only one thread to enter a code block at a time.
要是您想用一小块线程安全代码把要求同步的两个操作隔开,那么只使用一个同步块一般会更好些。
If you have two operations that require synchronization separated by a small block of thread-safe code, you are generally better just using a single synchronized block.
同步的方法和代码块允许线程在入口处锁定对象并在出口处解锁(针对方法或代码块)。
Synchronized methods and blocks allow a thread to lock an object on entry and unlock the object on exit (to the method or block).
即使代码块内部指令也许是乱序执行的,也不会对使用了同步的其它线程造成任何影响。
Even though processing of statements within blocks may be out of order, this cannot matter to other threads employing synchronization.
即使代码块内部指令也许是乱序执行的,也不会对使用了同步的其它线程造成任何影响。
Even though processing of statements within blocks may be out of order, this cannot matter to other threads employing synchronization.
应用推荐