How do i do this?
Create two (2) threads named by the user. Display their various states using getState( ).
In the main method:
Enable user input. Create two (2) threads. Ask the user to enter a name for each thread. Show the names and states of the threads. Start the threads. Have the threads sleep for half a second. Show the names and states of the threads. In the run( ) method, show the name and state of the current thread.
CodePudding user response:
We start off by creating a class called Multi (could be named anything) that extends the java.lang.Thread
. The run method will be called when start()
is called on the thread. We use java.util.Scanner
to read the user input and name the threads and pass the names in. Then in the run method we are sleeping for 500ms and printing the thread state.
public class Multi extends Thread {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread: " this.getName() " state: " this.getState());
}
public static void main(String args[]) {
Scanner inputScanner = new Scanner(System.in);
System.out.println("Enter Thread 1 Name:");
String name1 = inputScanner.nextLine();
System.out.println("Enter Thread 2 Name:");
String name2 = inputScanner.nextLine();
Multi t1 = new Multi();
t1.setName(name1);
t1.start();
Multi t2 = new Multi();
t2.setName(name2);
t2.start();
}
}
CodePudding user response:
Define a class that implements Runnable
.
Add a constructor that takes a String
object, the name submitted by a user.
In the run
method, call Thread#sleep
, and the report on thread state. Be aware that calls to System.out.println
across threads do not necessarily appear in chronological order. So also add to your output message the results of a call to Instant.now()
.
In modern Java, we rarely deal directly with the Thread
class. Instead we make use of the Executors framework added to Java 5.
Use Executors
utility class to instantiate an ExecutorService
of a kind of your choice. Submit instances of your Runnable
to the executor service.
Shutdown your executor service, and wait for submitted tasks to finish. See boilerplate code for this in the Javadoc.
All this has been covered many many times on Stack Overflow. So search to learn more, and to see fully coded examples including some authored by myself.