פורסם 2012 במרץ 413 שנים אם אני עושה סינכרון על אובייקט מסוים ובתוכו אובייקט אחר, האם גם אליו לא יכול לגשת תרד אחר כשתרד אחר שם.הנה דוגמא מקוד..(זה קטע די ארוך אבל תתעלמו מההתחלה ורק ה-2 שורות הראשונות של ה- run הן הענייןיש פה סיכנרון על this ושורה מתחת סינכרון על buffer שהוא שדה של this... public class ProtocolTask implements Runnable { private final ServerProtocol _protocol; private final StringMessageTokenizer _tokenizer; private final ConnectionHandler _handler; /** * the fifo queue, which holds data coming from the socket. Access to the * queue is serialized, to ensure correct processing order. */ private final Vector<ByteBuffer> _buffers = new Vector<ByteBuffer>(); public ProtocolTask(final ServerProtocol protocol, final StringMessageTokenizer tokenizer, final ConnectionHandler h) { this._protocol = protocol; this._tokenizer = tokenizer; this._handler = h; } // we synchronize on ourselves, in case we are executed by several threads // from the thread pool. public synchronized void run() { // first, add all the bytes we have to the tokenizer synchronized (_buffers) { while(_buffers.size() > 0) { ByteBuffer buf = _buffers.remove(0); this._tokenizer.addBytes(buf); } }
פורסם 2012 במרץ 513 שנים אני מקווה ששמת לב שהקוד ששמת פה לא ערוך בצורה קריאה כלל וכלללגבי השאלהאין צורך לעשות סינכרון בתוך מתודה מסונכרנת כי לעולם היא תופעל ע"י נים אחד בלבד.בנוסף לזה, כל מתודות של המחלקה Vector הן מסונכרנות (אני מנחש שזה למה אתה משתמש בה ולא ב ArrayList)
ארכיון
דיון זה הועבר לארכיון ולא ניתן להוסיף בו תגובות חדשות.