java - Multithread programming and incrementing a static variable -
i have read posts related problem not solve problem. code question in big java - object of cay horstmann. question asks counting word of several files using multithread programming , store combined words counting problem.
in order combined counter used static
variable incremented on each of iteration of counting words in threads. used reentrantlock()
make incrementing available 1 thread @ time. works fine except incrementing. seems static variable not incremented. tested number of lock()
, unlock()
each thread , match expected result static
variable not work properly.
is there explanation it? thank time , help.
my task class
:
import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; import java.util.concurrent.locks.lock; import java.util.concurrent.locks.reentrantlock; public class wordcount implements runnable { private string filename; scanner inputfile; private long counter; public volatile static long combinedcounter = 0; lock cclock; public wordcount(string aname) throws filenotfoundexception { try { this.cclock = new reentrantlock(); this.counter = 0; this.filename = aname; this.inputfile = new scanner(new file(this.filename)); } catch (filenotfoundexception e) {} } public void ccount() { cclock.lock(); try { combinedcounter++; /*synchronized (this) { combinedcounter++; }*/ } { cclock.unlock(); } } @override public void run() { try { while (inputfile.hasnext() && !thread.interrupted()) { synchronized (this) { ccount(); } counter++; inputfile.next(); thread.sleep(0); } system.out.printf("%s: %d\t\t%d\n", this.filename, this.counter,combinedcounter); } catch (interruptedexception e) {} } }
this client class
:
import java.io.filenotfoundexception; import java.util.concurrent.executorservice; import java.util.concurrent.executors; public class wordcountrunner { public static void main(string[] args) throws filenotfoundexception, interruptedexception { string = "a.txt"; string b = "b.txt"; executorservice pool = executors.newfixedthreadpool(2); ; try { runnable r1 = new wordcount(a); runnable r2 = new wordcount(b); pool.execute(r1); pool.execute(r2); while (!pool.isterminated()) { pool.shutdown(); } thread.sleep(100); system.out.print("***" + wordcount.combinedcounter); } catch (filenotfoundexception e) { } { pool.shutdown(); } } }
the lock not work because reentrantlock instance variable in wordcount class. so, each instance of class has own private lock , don't synchronize each other. easiest change make lock static, variable it's protecting.
Comments
Post a Comment