Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Main {
- public static void main(String[] args) throws InterruptedException {
- // 1. Enable user input
- Scanner scanner = new Scanner(System.in);
- // 2. Create two threads and 3. User Input for Thread name
- System.out.print("Name your first thread: ");
- String threadName1 = scanner.nextLine();
- System.out.print("Name your second thread: ");
- String threadName2 = scanner.nextLine();
- CustomThread thread1 = new CustomThread(threadName1);
- CustomThread thread2 = new CustomThread(threadName2);
- // 4. Show the names and states of the threads
- System.out.println(thread1.getName() + " is " + thread1.getState());
- System.out.println(thread2.getName() + " is " + thread2.getState());
- // 5. Start the threads
- System.out.println("\nStarting the thread...");
- thread1.start();
- thread2.start();
- // 6. Have the threads sleep for half a second
- Thread.sleep(500);
- // Wait for the threads to finish
- thread1.join();
- thread2.join();
- // Show the names and states of the threads after they have finished
- System.out.println("\nAfter sleep...");
- System.out.println(thread1.getName() + " is " + thread1.getState());
- System.out.println(thread2.getName() + " is " + thread2.getState());
- scanner.close();
- }
- }
- class CustomThread extends Thread {
- CustomThread(String name) {
- super(name);
- }
- @Override
- public void run() {
- // Show the name and state of the current thread
- System.out.println(getName() + " is " + getState());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment