0
Thread thbus = new Thread(bus);
bus.setName("Bus"+ thbus.getId());

Thread thmechanics = new Thread(bus);
bus.setMechanicsName("Mechanic "+ thmechanics.getId());

thbus.start();

These generate threads that are in my other classes. The "Mechanic "+ thmechanics.getId() line will print "Mechanic" + a random number. I want to know if there is a way to use the .getId() to print random number between (1-5).

Bucket
  • 7,415
  • 9
  • 35
  • 45
Ben
  • 29
  • 3
  • *"Is there a way to get random number between (1-5)"* Did you try a web search? You'll find a gazillion answers. – Andreas May 04 '18 at 20:34

1 Answers1

3

Easy/pragmatically done, by using the % (modulo) operator:

(thread.getId() % 5 ) + 1

welcome ;)

Since mod-in-java-produces-negative-numbers and I cannot guarantee, that thread id's always positive, even:

Math.abs(thread.getId() % 5) + 1

..and even better(!):

(thread.getId() % 5 + 5) % 5 + 1

...could make sense.

xerx593
  • 12,237
  • 5
  • 33
  • 64