简体   繁体   中英

multi thread safe class

Question:

A) Write a thread safe class with methods doA(), doB(), doC(). Each of these methods must report the method name, time of invocation, and calling thread name.

B) Write a multi threaded driver that spawns 4 threads, and each thread must call every method – doA(), doB(), doC() – 10 times

I am assuming that it means doA(), doB(), doC() must be safe. But none of them mutate the shared state within the object, they just read object state such as method name, thread name and running time. So, do I need synchronize each method? For the counter within each thread, it is not shared.

I am a little confused here, which of state of the object needs protection?

Edit: Do we need a mechanism to assure the running sequence of doA(), doB(), doC()? I dont think so.

From the sounds of it, your object will have no mutable state at all. Objects without mutable state are usually (not always, but usually) thread-safe without any additional locking. Of course, if there's additional requirements that do imply mutable state, the answer would be different.

How are you reporting the information? If it's to a console or any other resource that's independent of thread, there's your shared "state". Sort of. Some mechanisms for writing to a console will buffer lines, so you may not have problems, but over multiple lines you'll have to make sure that two don't write to it at the same time. For example, if I were to print:

Thread: A
Method: doA
Running Time: 4.6s

Then I'd want to make sure another thread doesn't start half-way through. Otherwise you may end up with something like this:

Thread: A
Thread: B
Method: doB
Running Time: 4.6s
Method: doA
Running Time: 3.2s

Not so helpful.

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