Name = Thread-0
Name = main
Name = Thread-0
Name = main
Name = main
This is a version of the results I am getting when I run the program.
I don't understand why it displays Name = main.
After all, we are starting a new ThreadNamePrinter object named tnp which creates and starts a new thread object.
I assume it has something to do with the Thread.currentThread() assignment to variable t but doesn't that assign the newly created current thread to that variable?
Therefore, shouldn't the answer be
Name = Thread-0
Name = Thread-0
etc?package com.codegym.task.task16.task1621;
/*
Thread.currentThread always returns the current thread
*/
public class Solution {
static int count = 5;
public static void main(String[] args) {
ThreadNamePrinter tnp = new ThreadNamePrinter();
tnp.start();
for (int i = 0; i < count; i++) {
tnp.printMsg();
}
}
public static class ThreadNamePrinter extends Thread {
public void run() {
for (int i = 0; i < count; i++) {
printMsg();
}
}
public void printMsg() {
Thread t = Thread.currentThread(); // The current thread should be assigned to the variable t
String name = t.getName();
System.out.println("Name = " + name);
// Add sleep here
try{
t.sleep(1000);}catch (InterruptedException e){}
}
}
}