I am to create a program which creates multiple threads, has them do work in parallel, and terminates when the last thread is finished, sounds simple right?
Here is the curve... I am supposed to create thread objects using scanner input, and I am at a loss
When I run my code, I get it to run once per item, but given the input It should read each item n number of times: code is below, I really just don't know where to go from here. I am greatful for any advice.

import java.io.*;
import java.util.*;
import java.awt.*;

/**
 *
 * @author tricket_7
 */
class MyThread extends Thread{
    public void run(){
         Scanner input = new Scanner(System.in);

         //insert up to 10 countries
        System.out.println("How many countries are being supported? ");
        int[] numCountries = new int[input.nextInt()];

        String[] names = new String[10];
        int[] numCheers = new int[10];


        for(int i = 0; i < numCountries.length; i++){ 

            //creates each thread object
            System.out.println("Enter country name: "); 
            names[i] = input.next();

            //creates number of times thread runs
            System.out.println("Enter Number of Cheers: ");
            numCheers[i] = input.nextInt();
        }

        for(int i=0; i<numCountries.length;i++){               
            System.out.println("Go " + names[i] + "!");
    }
    }

    }
public class CheersThread{
 public static void main(String[] args) throws InterruptedException {

 //How do I take in multiple threads here?
 MyThread t = new MyThread();

//How do I start the multiple threads here?

 t.start();

    }
}

Recommended Answers

All 24 Replies

MyThread t = new MyThread();
t.start();
MyThread t2 = new MyThread();
t2.start();

could be a good start.

Even if there are n threads? It could be 1 to 10 threads

MyThread mThread;
List<MyThread> lists = new ArrayList<>();
for ( int i = 0; i < desiredNumber; i++ ){
  mThread = new MyThread();
  mThread.start();
  lists.add(mThread);
}

if you don't need to store the threads you run:

for (int i = 0; i < desiredNumber; i++){
  new MyThread().start();
}

This problem breaks down into two distinct stages:
1. Collect all the info from the user (10 names, 10 counts) and store those in two arrays...
then...
2. Using that info stored in the arrays, use a loop (see above) create and start 10 threads

You can't mix the user input and starting the threads because the user will take so long to type that any previous threads wil have finished long before you start the next one.

when I enter the thread into a loop it asks me how many countries 10 times, I modified my code, and now it shows:
Enter num of countries: I enter 3
Enter country name: USA
Enter num of cheers: 2
Enter country name: Russia
Enter num of cheers: 3

and outputs:
Go Usa
go russia

but it should output each one for the indicated number of cheers, then terminate when the thread is complete.

import java.io.*;
import java.util.*;
import java.awt.*;
import java.util.List;
import java.util.ArrayList;
/**
 *
 * @author tricket7
 */


class MyThread extends Thread{
    public void run(){
        List<String>name = new ArrayList<String>();
        List<Integer>numCheers = new ArrayList<Integer>();
        List<MyThread>cheersThread = new ArrayList<MyThread>();

        Scanner input = new Scanner(System.in);
        System.out.println("How many countries are supported? ");
        int numCountries = input.nextInt();


        for(int i = 0; i < numCountries; i++){
            try{
        System.out.println("Enter country Names: ");
        String countryNames = input.next();
        name.add(countryNames);
        System.out.println("Enter number of cheers: ");
        int cheerCount = input.nextInt();
        numCheers.add(cheerCount);

                Thread.sleep((int)Math.random()*5000);
            }
            catch(InterruptedException e){
                System.out.println(e);
            }
        }

        for(int i = 0;i<numCheers.size();i++){           
         System.out.println("Go " + name.get(i)  + "!");
    }
} 
}
 public class CheersThread {  


 public static void main(String[] args) throws InterruptedException {

    MyThread cheers = new MyThread();   
    cheers.start();

}
 }

Never mind my last post, I came to understand what you were saying.... I am almost there, and will gladly post my solution when I get it.

Ok, I followed your advice and this is what I get, but my next question is how do I get it to print out the country names the number of times the cheers are entered?
For example....
Enter number of countries? 1
Enter name: USA
Enter number of cheers: 3
it should output....
Go USA !
Go USA !
Go USA !

import java.io.*;
import java.util.*;
import java.awt.*;
import java.util.List;
import java.util.ArrayList;
/**
 *
 * @author tricket7
 */


class MyThread extends Thread{

    public void run(){
       try{
       Thread.sleep((int)Math.random()*5000);
        System.out.println("Go " + "!");
       }catch(InterruptedException e){
           System.out.println(e);
       }
       }

} 

 public class CheersThread {  


 public static void main(String[] args) throws InterruptedException {


      List<String>name = new ArrayList<String>();
      List<Integer>numCheers = new ArrayList<Integer>();


        Scanner input = new Scanner(System.in);
        System.out.println("How many countries are supported? ");
        int numCountries = input.nextInt();


        for(int i = 0; i < numCountries; i++){

        System.out.println("Enter country Names: ");
        String countryNames = input.next();
        name.add(countryNames);
        System.out.println("Enter number of cheers: ");
        int cheerCount = input.nextInt();
        numCheers.add(cheerCount);
            }
        int sum = 0;
           for(int i = 0;i<numCheers.size();i++){     
               sum = sum + numCheers.get(i);
               System.out.println(name.get(i));
           }      

    for(int i = 0;i < sum; i++ ){
        new MyThread().start();

    }

}
 }

That's getting a lot closer!

When you create a new instance of MyThread that instance needs to know (1) the country name and (2) how many times to cheer. Then it can use a loop to print the country name the right number of times.
That implies that MyThread needs two instance variables - countryName and numberOfCheers. You can then write a constructor that accepts values for both those variables. Then on line 56 where you create the new instance of MyThread you can pass in the country name and the number of cheers.

so I am going to write a constructor that accepts name, and numCheers
and pass it to MyThread();

new MyThread(getName(), getNumCheers()).start();

like above:

Something like that...
But your names and nums are in two array lists, so you need to pass the elements of those lists to each constructor

Ok, under MyThread extends Thread, I created the variables, am I on the right track? Wont I be passing the arrays to MyThread instead of String and int?
then in my main method I have MyThread(name.get(i), numCheers.get(i)).start();
I am still uncertain about passing the arrayList elements to each constructor

Btw, I really appreciate your patience and your help, You are making it so nice for a beginner like myself to work on this and try to understand what I am doing.

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.*;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Christie
 */

class MyThread extends Thread{
    int numCheers;
    String name;

    MyThread(String name, int numCheers){
        this.numCheers = numCheers;
        this.name = name;
    }



    public void run(){
       try{
       Thread.sleep((int)Math.random()*5000);
        System.out.println("Go " + Thread.currentThread().getId() + "!");
      //  System.out.println(getName());
       }catch(InterruptedException e){
           System.out.println(e);
       }
       }

} 
public class Cheers {


    public static void main(String[] args) throws InterruptedException {

      List<String>name = new ArrayList<String>();
      List<Integer>numCheers = new ArrayList<Integer>();


        Scanner input = new Scanner(System.in);
        System.out.println("How many countries are supported? ");
        int numCountries = input.nextInt();

        if(numCountries <= 10){        
        for(int i = 0; i < numCountries; i++){

        System.out.println("Enter country name: ");
         String countryNames = input.next();
         name.add(countryNames);
        System.out.println("Number cheers: ");
        int cheerCount = input.nextInt();
        numCheers.add(cheerCount);       

        } }else{
            System.out.println("Countries supported must be 10 or less: ");
        }

        int sum = 0;
           for(int i = 0;i<numCheers.size();i++){     
               sum = sum + numCheers.get(i);            

           }      
         System.out.println(sum); 
    for(int i = 0;i < sum; i++ ){    

        new MyThread(name.get(i), numCheers.get(i)).start();

    }
    }
}

That all looks like good progress to me. There may still be mistakes (I didn't study every line) but what you are doing with the constrcutor and passing the values looks right. Have you tried it yet? Never be afraid to try to compile and run your code.

In your run method you could print the name (the thread ID won't tell you anything useful), and don't forget to have a loop that does the print numCheers times.

Ok! Great! I am getting somewhere..... When I enter country name: and num Cheers:
ex Russia 2, china 2 , usa 2

It does output
Go Russia!
Go Russia!
Go China!
Go china!
Go USA!
Go USA!

but I think it should mix them up, not do one, then complete one before going to the next....

It should not always be the same but should be:
Go USA!
Go China!
Go Russia!
Go China!
Go China!
Go Russia!

until all have been used

Argg! Cancel last post, I got it working but getting this error:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
Go Russia!
Go Usa!
Go china!
Go Russia!
Go Usa!
Go china!
Go Usa!
Go china!
    **at java.util.ArrayList.rangeCheck(ArrayList.java:604)**
Go china!
    **at java.util.ArrayList.get(ArrayList.java:382)
    at Cheers.main(Cheers.java:59)**
Java Result: 1

here is my finished code with above error

import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author tricket_7
 *
 * 2/19/14
 */

class MyThread extends Thread{
    int numCheers;
    String name;     

    MyThread(String name, int numCheers){

        this.numCheers = numCheers;
        this.name = name;
    }

    public void run(){
       try{

       //loops through the arrayList number of cheers to start threads and print the message for each one
       for(int i = 0; i< numCheers;i++){
           MyThread.sleep(2 + (long)Math.random()*5000);
           System.out.println("Go " + name + "!");
       }
       }catch(InterruptedException e){
           System.out.println(e);
       }
       }      
} 
public class Cheers {

    public static void main(String[] args) throws InterruptedException {

        //array list to store the name of each country supported at the bar
      List<String>name = new ArrayList<String>();

      //array list to store the number of cheers for each country entered
      List<Integer>numCheers = new ArrayList<Integer>();

        //Scanner takes in user input
        Scanner input = new Scanner(System.in);

        //Enter how many countries will be supported
        System.out.println("How many countries are supported? ");
        int numCountries = input.nextInt();

       //validates that no more than 10 countries were entered
        if(numCountries < 10){ 

        //loops through the number of countries entered to add the elements to the arrays
        for(int i = 0; i < numCountries; i++){


        System.out.println("Enter country name: ");
         String countryNames = input.next();

         //stores the country names into the array lis
         name.add(countryNames);

        System.out.println("How many cheers? ");
        int cheerCount = input.nextInt();

        //stores the number of cheers each country has into an array list
        numCheers.add(cheerCount);       

        } 

        //loop to create a new thread for each country
         for(int i = 0;i <= numCountries; i++ ){ 

       //creates thread and takes the country name and number of cheers as parameters
       MyThread c =  new MyThread(name.get(i), numCheers.get(i));

       //starts thread goes to run function
       c.start();

    }
        }else{

            //error message if more than 10 was entered for countries supported
            System.out.println("Countries supported must be 10 or less: ");
        }       

    }
}

plus I noticed when I enter 1 country with 2 cheers it outputs 3 times...

Ok nevermind, I ve got it figured out. Thanks so much for the help

Can I ask though shouldnt there be random pauses between the outputs of the countries? They all pop up in 8 seconds, but they should have random pauses in between all of them

Can I ask though shouldnt there be random pauses between the outputs of the countries? They all pop up in 8 seconds, but they should have random pauses in between all of them

Looks like a problem in your use of Random for the sleeps - you cast the floating point random number to an integer (therefore always zero) before multiplying it by 5000.

You started a new thread for no apparent reason, and without marking this solved - we'll continue the discussion here.

Please read my previous post. Your latest code makes exactly the same mistake

s = 2+((int)Math.random());

To explain in more detail:

Math.random() returns a floating point number >=0.0, <1.0
If you cast that to an integer type it will lose any fractional parts, so
(int) Math.random() will ALWAYS be zero, and s will always be 2
You must multiply by 5000 FIRST. That gives you a floating point number >=0.0 <5000.0, which you can then convert safely to integer with the result >=0, <= 4999

You just created a new topic with exactly the same question and exectly the same error. If you persist in ignoring the DaniWeb rules you will get infracted - possibly leading to a ban.

Do not post the same question multiple times http://www.daniweb.com/community/rules

I am soo sorry, that was my error in not reading.

Thank you JamesCherrill, that solved the problem at hand, again thank you for your patience and I apologize for my mistake on the repost. The first time I thought I deleted it, but when I read you message I realized my faux paus.
I will be mindful in the future about my posts.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.