Reputation: 227
Hi I've a code as below.
class main{
main()
{
myThread1 mt1 = new myThread1();
myThread2 mt2 = new myThread2();
mt1.start();
mt2.start();
mt1.join();
mt2.join()
System.out.println(access.sb.toString());
}
}
class myThread1{
run(){
access.grow(" IJKLMNOP ");
}
}
class myThread2{
run(){
access.grow(" ABCDEFGH ");
}
}
class access{
StringBuilder sb = new StringBuilder();
void grow(str)
{
sb.append(str);
}
}
**Ignore errors
Output:
ABCDE IJKLMFGHFGH
Expected Output should be one after the other, or vice. I figured it out that, it is due to random access to function grow
by both the threads. Is there any process so that I can allow access to function grow
only one thread at an instance.
Upvotes: 1
Views: 43
Reputation: 1
For better performance use synchronize block
void grow(str)
{
synchronize(sb){
sb.append(str);
}
}
also u can use concurrency pkg lock class
Lock lock = new ReentrantLock();
void grow(str)
{
try{ lock.lock();
sb.append(str);
finally(){
lock.unlock();
}
}
Upvotes: 0
Reputation: 77044
Marking grow
as synchronized
will cause a particular instance of access
to serialize calls to grow
amongst threads:
synchronized void grow() {
...
}
Another approach would be to enqueue work onto some flavor of a thread-safe Queue
(typically some kind of BlockingQueue
) and then to read work from the queue on a different thread, but that might not be necessary given the context you've provided.
Upvotes: 4