473,406 Members | 2,867 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Synchronized threads

I need to synchronize all the threads to add all the numbers.
Threads are created, but not started immediately. When the threads do start, they must start simultaneously, without preferential treatment. That is to say, when the threads are finally allowed to start, Thread-1 should not always be the one to be scheduled on the CPU first. This should be addressed using threading constructs (mutex, semaphore, monitors, etc), and never ever managed by a call to random(), yield(), nor other convoluted equitability scheme.
Here is my code.
Expand|Select|Wrap|Line Numbers
  1. public class Adder {
  2.   public int[] array;
  3.   private int sum = 0;
  4.   private int index = 0;
  5.   private int number_of_threads = 10;
  6.   private int threads_quit;
  7.   static final int ARRAYSIZE = 10000;
  8.   public Adder() {
  9.     threads_quit = 0;
  10.     array = new int[ARRAYSIZE];
  11.     initializeArray();
  12.     startThreads();
  13.   }
  14.  
  15.   public synchronized int getNextIndex() {
  16.     if (index < ARRAYSIZE) return (index++); else return (-1);
  17.   }
  18.  
  19.   public synchronized void addPartialSum(int partial_sum) {
  20.     sum += partial_sum;
  21.     if (++threads_quit == number_of_threads)
  22.       System.out.println("The sum of the numbers is "+sum);
  23.  
  24.   }
  25.   private void initializeArray() {
  26.     int i;
  27.     for (i=0; i < ARRAYSIZE ; i++) array[i] = i+1;
  28.   }
  29.   public synchronized void startThreads() {
  30.     int i = 0;
  31.     for (i=0; i< number_of_threads; i++) {
  32.       AdderThread at = new AdderThread(this,i);
  33.       at.start();
  34.     }
  35.   }
  36.  
  37.   public static void main(String args[]) {
  38.     Adder a = new Adder();
  39.   }
  40. }
  41.  
  42. class AdderThread extends Thread {
  43.   int partial_sum = 0;
  44.   Adder parent;
  45.   int number;
  46.   public AdderThread(Adder parent, int number) {
  47.     this.parent = parent;
  48.     this.number = number; 
  49.   }
  50.  
  51.   public synchronized void run() {
  52.     int index = 0;
  53.     index = parent.getNextIndex() ;
  54.     while (index != -1) {
  55.         partial_sum = partial_sum + parent.array[index];
  56.         index = parent.getNextIndex();
  57.     }
  58.  
  59.     System.out.println("Partial sum from thread " + number + " is " +
  60.         partial_sum);
  61.     parent.addPartialSum(partial_sum);
  62.   }
  63. }
Mar 9 '07 #1
4 1569
r035198x
13,262 8TB
I need to synchronize all the threads to add all the numbers.
Threads are created, but not started immediately. When the threads do start, they must start simultaneously, without preferential treatment. That is to say, when the threads are finally allowed to start, Thread-1 should not always be the one to be scheduled on the CPU first. This should be addressed using threading constructs (mutex, semaphore, monitors, etc), and never ever managed by a call to random(), yield(), nor other convoluted equitability scheme.
Here is my code.

public class Adder {
public int[] array;
private int sum = 0;
private int index = 0;
private int number_of_threads = 10;
private int threads_quit;
static final int ARRAYSIZE = 10000;
public Adder() {
threads_quit = 0;
array = new int[ARRAYSIZE];
initializeArray();
startThreads();
}

public synchronized int getNextIndex() {
if (index < ARRAYSIZE) return (index++); else return (-1);
}

public synchronized void addPartialSum(int partial_sum) {
sum += partial_sum;
if (++threads_quit == number_of_threads)
System.out.println("The sum of the numbers is "+sum);

}
private void initializeArray() {
int i;
for (i=0; i < ARRAYSIZE ; i++) array[i] = i+1;
}
public synchronized void startThreads() {
int i = 0;
for (i=0; i< number_of_threads; i++) {
AdderThread at = new AdderThread(this,i);
at.start();
}
}

public static void main(String args[]) {
Adder a = new Adder();
}
}

class AdderThread extends Thread {
int partial_sum = 0;
Adder parent;
int number;
public AdderThread(Adder parent, int number) {
this.parent = parent;
this.number = number;
}

public synchronized void run() {
int index = 0;
index = parent.getNextIndex() ;
while (index != -1) {
partial_sum = partial_sum + parent.array[index];
index = parent.getNextIndex();
}

System.out.println("Partial sum from thread " + number + " is " +
partial_sum);
parent.addPartialSum(partial_sum);
}
}
1.)Plese use code tags when posting code
2.)So where is your problem?
Mar 9 '07 #2
The threads are all not executing at the same time where a couple threads will do all the work and some of the threads will do nothing at all. I am trying to make it so all the threads evenly do the work load of adding all the numbers up.
Mar 9 '07 #3
horace1
1,510 Expert 1GB
The threads are all not executing at the same time where a couple threads will do all the work and some of the threads will do nothing at all. I am trying to make it so all the threads evenly do the work load of adding all the numbers up.
you could try putting a sleep in the run() method, e.g.
Expand|Select|Wrap|Line Numbers
  1.   public synchronized void run() {
  2.     int index = 0;
  3.     index = parent.getNextIndex() ;
  4.     while (index != -1) {
  5.         partial_sum = partial_sum + parent.array[index];
  6.         index = parent.getNextIndex();
  7.         try {Thread.sleep(1);} catch (InterruptedException e){}
  8.     }
  9.  
or try
Expand|Select|Wrap|Line Numbers
  1.   public synchronized void run() {
  2.     int index = 0;
  3.     index = parent.getNextIndex() ;
  4.     while (index != -1) {
  5.         partial_sum = partial_sum + parent.array[index];
  6.         index = parent.getNextIndex();
  7.         notifyAll(); wait(); 
  8.     }
  9.  
Mar 9 '07 #4
I am supposed to get it all synchronized without using the sleep or wait or interrupts. The threads are to be synchronized without them
Mar 19 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: John Thorner | last post by:
Hi, I am creating a new thread for each of the connections to the server: public class Node_C { .... while (listening) { Socket client_socket = server_socket.accept(); Node_CThread node ...
5
by: Max Ischenko | last post by:
Hi, I wrote simple implementation of the "synchronized" methods (a-la Java), could you please check if it is OK: def synchronized(method): """ Guards method execution, similar to Java's...
5
by: Seeker | last post by:
Hello, I've read conflicting posts about . Does it or does it not lock the entire object? In my simple test it appears to block just the method but I wouldn't exactly call my meager test...
8
by: ASP.Net programmer | last post by:
Hi, I have a few methods in a class that I want to synchronize (make sure they can't be used at the same time by multiple threads). As a Java programmer I just do this: public synchronized...
0
by: Dave Coate | last post by:
I am working on a generic way to launch multiple similar processes (threads) at once, but limit the number of threads running at any one time to a number I set. As I understand it the following...
1
by: KK | last post by:
Dear All I have a class whose methods are getting called from multiple threads in my application. For example class DataDistribution { private ArrayList datset; public DataDistribution() {...
2
by: semedao | last post by:
Hi, what is the best way to Synchronized threads on classes that use or inherit from Generics ? (Dictionary for example) Thanks. (and where is the *Class*.Synchronized method for them ?)
1
by: John Vottero | last post by:
If I create a synchronized TextWriter with TextWriter.Synchronized(...), how do I make sure that all the writes are done before I Close()? Do I have to invent that synchronization mechanism...
19
by: =?ISO-8859-1?Q?Nordl=F6w?= | last post by:
I am currently designing a synchronized queue used to communicate between threads. Is the code given below a good solution? Am I using mutex lock/unlock more than needed? Are there any resources...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.