Java同步 [英] Java Synchronization

查看:80
本文介绍了Java同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是什么:

synchronized (this) {
    // ...some code...
}

有用吗?
(你能写一个例子吗?)

good for? (Could you write an example?)

推荐答案

它可以防止多个线程运行大括号中包含的代码。当一个线程正在运行该代码时,其余部分将被阻止。当第一个线程完成时,其中一个被阻塞的线程将运行同步代码,依此类推。

It prevents multiple threads from running the code contained within the braces. Whilst one thread is running that code, the remainder are blocked. When the first thread completes, one of the blocked threads will then run the synchronised code, and so on.

为什么要这样做?块内的代码可以修改对象,使得它们处于不一致状态,直到块退出。所以进入的第二个线程会发现不一致的对象。从那时起就会发生混乱。

Why do you want to do this ? The code within the block may modify objects such that they're in an inconsistent state until the blocks exits. So a second thread coming in would find inconsistent objects. From that point on chaos ensues.

一个例子是从一个池中删除一个对象并将其插入另一个池中。第二个线程可能会在第一个线程移动对象时运行,然后找到两个集合中引用的对象,或者两者都没有。

An example would be removing an object from one pool and inserting it in another. A second thread might run whilst the first thread is moving the object, and subsequently find the object referenced in both collections, or neither.

您也可以使用此机制来限制访问资源的多个线程,这些资源被设计为由一个资源使用(例如,一个简单的数据库)。

You can also use this mechanism to restrict multiple threads from accessing a resource designed to be used by one resource (e.g. a trivial database, for example).

这篇关于Java同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆