codetoad.com
  ASP Shopping CartForum & BBS
  - all for $20 from CodeToad Plus!
  
  Home || ASP | ASP.Net | C++/C# | DHTML | HTML | Java | Javascript | Perl | VB | XML || CodeToad Plus! || Forums || RAM 
Search Site:
Search Forums:
  Data sharing in java thread()  ericwi at 06:20 on Monday, November 13, 2006
 

Hi all,

I am new to this multithreading programming. I am working on an exercise where I was supposed to code two Thread objects accessing the same variable such that when one Thread changed the variable value will also change the variable value of another Thread. Is this possible?


Thanks

  Re: Data sharing in java thread()  crwood at 18:29 on Monday, November 13, 2006
 


public class Synching {
int counter = 0;
int maxCount = 20;

public static void main(String[] args) {
Synching synching = new Synching();
new Worker(synching, "one").start();
new Worker(synching, "two").start();
}

synchronized void increment(Worker w) {
System.out.printf("%s incrementing count to %d%n",
w, ++counter);
}

boolean finished() {
return counter >= maxCount;
}
}

class Worker implements Runnable {
Synching synching;
String name;
Thread thread;
boolean working = false;

Worker(Synching s, String name) {
synching = s;
this.name = name;
}

public void run() {
while(working) {
if(synching.finished())
stop();
else
synching.increment(this);
}
}

void start() {
if(!working) {
working = true;
thread = new Thread(this);
thread.start();
}
}

void stop() {
working = false;
thread = null;
System.out.printf("%s stopped%n", this);
}

public String toString() {
return name;
}
}









CodeToad Experts

Can't find the answer?
Our Site experts are answering questions for free in the CodeToad forums








Recent Forum Threads
•  selective copying from a file
•  Perl giving memory error in Windows
•  optimize my very simple javascript.
•  How create regexpr
•  Run Time Error
•  jsp login
•  Form SELECT auto post or get of selection
•  Re: Data sharing in java thread()
•  how to capture screen from a webpage using javascript


Recent Articles
ASP GetTempName
Decode and Encode UTF-8
ASP GetFile
ASP FolderExists
ASP FileExists
ASP OpenTextFile
ASP FilesystemObject
ASP CreateFolder
ASP CreateTextFile
Javascript Get Selected Text


© Copyright codetoad.com 2001-2006