开发者

java threads concept [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. Fo开发者_Go百科r help clarifying this question so that it can be reopened, visit the help center. Closed 10 years ago.

when i am reading java threads concept i had see a statement i.e "when it comes to threads,very little guaranteed" .can any one explain this in brief.


It is probably trying to explain the fact the order of execution of statements in two threads is not guaranteed and you can not rely on it i.e. the order might be in a particular way on one system and might be completely different on a machine with a different hardware. Its not even guaranteed on the same system you will get the same sequence in multiple runs.


I think what she means is that very little is guaranteed in terms of when a thread will start and finish executing, unless you explicitly synchronize them in some way. You also lose guarantees about data safety if multiple threads read and write the same data simultaneously.


I haven't read the book myself and it depends on the wider context. But it's probably talking about thread safety and how you need to take extra steps in a multithreaded environment to ensure your code is thread safe - preventing things such as deadlock, livelock and race hazards (all of which can manifest themselves in annoying, hard to track down ways that cause a lot of time and headache.) So trying to prevent these happening in the first place is much better than dealing with the effects later.

A typical (simple) example could be demonstrated by a class A that contains two fields, x and y. When the following method is called x and y are both incremented:

public void inc() {
  x++;
  y++;
}

Now ordinarily you'd assume that this is an atomic operation, the only result of calling this method is that x and y are both incremented. However, in a multithreaded environment this cannot be automatically guaranteed. There's a chance that after incrementing x, the current thread will be yielded and another one may come in and use that object in an invalid state, potentially causing problems.

That's just one example, there's many other different types and categories. In short, you don't get any form of thread safety for free so very little is guaranteed and if writing multithreaded code you need to learn how to cope with these problems.

I'd recommend the Java concurrency in practice book as a further read, it's a great book that explains threading problems very well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜