SenpaiZero

Untitled

Jun 5th, 2024
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4.  
  5. public static void main(String[] args) throws InterruptedException {
  6. // 1. Enable user input
  7. Scanner scanner = new Scanner(System.in);
  8.  
  9. // 2. Create two threads and 3. User Input for Thread name
  10. System.out.print("Name your first thread: ");
  11. String threadName1 = scanner.nextLine();
  12. System.out.print("Name your second thread: ");
  13. String threadName2 = scanner.nextLine();
  14.  
  15. CustomThread thread1 = new CustomThread(threadName1);
  16. CustomThread thread2 = new CustomThread(threadName2);
  17.  
  18. // 4. Show the names and states of the threads
  19. System.out.println(thread1.getName() + " is " + thread1.getState());
  20. System.out.println(thread2.getName() + " is " + thread2.getState());
  21.  
  22. // 5. Start the threads
  23. System.out.println("\nStarting the thread...");
  24. thread1.start();
  25. thread2.start();
  26.  
  27. // 6. Have the threads sleep for half a second
  28. Thread.sleep(500);
  29.  
  30.  
  31. // Wait for the threads to finish
  32. thread1.join();
  33. thread2.join();
  34.  
  35. // Show the names and states of the threads after they have finished
  36. System.out.println("\nAfter sleep...");
  37. System.out.println(thread1.getName() + " is " + thread1.getState());
  38. System.out.println(thread2.getName() + " is " + thread2.getState());
  39.  
  40. scanner.close();
  41. }
  42. }
  43.  
  44. class CustomThread extends Thread {
  45.  
  46. CustomThread(String name) {
  47. super(name);
  48. }
  49.  
  50. @Override
  51. public void run() {
  52. // Show the name and state of the current thread
  53. System.out.println(getName() + " is " + getState());
  54. }
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment