• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Threads and valueOf() method

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello, I'm really struggling to understand this homework problem and the concepts behind it:

Write a program called MyQ12Class.java that takes in an integer as an argument, creates that many Threads, and prints out the name of the Threads to the standard output.
Example: "Hi, I am Thread1", "Hi, I am Thread2", and so on and so forth.

Remember to covert the element in args[0] into an Integer, using the valueOf() method.
Remember that if the valueOf method fails it can throw Exceptions, so you will need a try/catch block.

Override the run method to print the Thread name to the standard output. The teacher provided me some help with this code, but I'm not understanding the concepts behind it:


I guess my main questions are:

What type of exceptions are appropriate?
How to instantiate the threads?

Any help would be greatly appreciated!
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

What type of exceptions are appropriate?



Simply put, you need to catch the exceptions that are declared in the method you are calling:

Using the String class as an example, it has the following method:



If you want to call that method on a String you need to catch what is listed in the throws clause. In this case you must catch(UnsupportedEncodingException e)

It's a minor detail at this stage in your learning, but understand that any exception that is a direct or indirect subclass of RuntimeException is optional. You can catch it or not, up to you. Your teacher will probably give you extra points if you catch any RuntimeExceptions the javadoc mentions for the given method.

How to instantiate the threads?



Sounds like the teacher wants you to override the run method, in which case you need to learn how to create a subclass. You'll subclass Thread and override the run method. Then you need to instantiate the subclass with the new keyword and choosing the appropriate constructor.

Here's an example of subclassing Object and overriding toString



reply
    Bookmark Topic Watch Topic
  • New Topic