What the use of Thread constructor with string param? - java

Looking at the Thread constructors, I see there is one that takes single string parameter. I have the below code, which is kind of useless. I would like to know, how to make a fruitful use of this constructor and make something actually run
public class ThreadTest {
public static void main(String[] args) {
Thread t = new Thread("abc");
t.start();
System.out.println("Complete");
}
}
Or Is it not supposed to be used the way I demonstrated above?
I perfectly know how to write multiple threads and execute :), I am just trying to understand the correct use of this constructor? Should it only be used by calling super(name) by extending Thread and not by the way I am using it above.

The thread class in itself doesn't do all that much. You have to extend it or construct it around a runnable to make it perform a task when run. From the doc:
start(): "Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread."
run(): "If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns."
Therefore constructing a new thread in your fashion and starting it does nothing. One use of the Thread(String) constructor is in subclasses:
public class Worker extends Thread{
public Worker(int numb){
super("worker-"+numb);
}
#Override
public void run(){
//Stuff this thread actually does when run
//....
for(int i = 0; i < 10; i++)
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
To answer your second question in the comments, this is how you would write code that's executed in parallel. Consider the above class plus this main method:
public static void main(String[] args){
Worker w1 = new Worker(1);
Worker w2 = new Worker(2);
w1.start();
w2.start();
}
The run methods of w1 and w2 will be executed in parallel. The order of the print statements will vary between executions of the main method.

This particular constructor is used to specify the 'name' of a thread, which can later be used to distinguish between instances of a specific thread type.
From the official Java API documentation;
Thread
public Thread(String name)
Allocates a new Thread object. This
constructor has the same effect as Thread (null, null, name).
Parameters: name - the name of the new thread
Once you have allocated a Thread a name, you can call the getName() method on the Thread instance to return the name it was given when it was created. This can be useful for debugging or for distinguishing between instances of of the same Thread subclass type.
Extra Reading:
Official Guide - Defining and Starting a Thread

If you simply call this constructor you get a Thread which does nothing. Why? Look at the source code of java.lang.Thread. It has a private Runnable target; class variable. When you call this constructor, the target variable remains set to null (because this constructor simply sets the Thread's name).
Also, the run() method of java.lang.Thread looks like this:
public void run() {
if (target != null) {
target.run();
}
}
So it means that this run() method will do nothing as target is null.
In order to create/start a Thread which really does something useful read here:
The Java tutorial - how to run a thread?

Related

How does multithreading method invocation work

I am using java.
I have an instance a of class A which has a public method foo() running and 2 other threads - threadB and threadC, all running at the same time.
here's class A
public class A {
int val = 0
public void foo(int incValue) {
a += incValue;
}
public static void main (String arg[]) {
MyThread a = new MyThread(this);
new Thread(a).start();
MyThread b = new MyThread(this);
new Thread(b).start();
}
}
here's the thread definition for threadB and threadC:
public class MyThread implements Runnable {
A main = null;
public MyThread(A main) {
this.main = main;
}
public callFoo(int incValue) {
main.foo(incValue);
}
#Override
public void run() {
//valToInc can be a value from a GUI form.
callFoo(valToInc);
}
}
If in threadB invokes callFoo(1) and threadC invokes callFoo(3) at the same time, then:
- Which thread will be able to call the method first?
- What is the result of the val in main class after both executions?
- Will the execution of the method for each thread happen concurrently or one after another?
There is absolutely no difference in how the JVM will invoke two methods "in parallel".
In other words: if you want to know what happens when a method is called, you can look here.
When a method is called "twice" in parallel, then that whole thing ... just happens twice!
Things become interesting when that method is making updates on that class, or in other objects! (like changing a field of your object, or appending a value to a list, ... )
You see, the real complexity of multi-threading is not about running some code in parallel. The real issue is what happens to "shared data".
If you find my answer to general; sorry - that is probably the best you can expect for such a generic question.
If [] threadB invokes callFoo(1) and threadC invokes callFoo(3) at the same time, then: - Which thread will be able to call the method first?
Threads run independently of each other. If there is no synchronization (there's none in your example), then any number of threads can be in calls to the same method at the same time.
Whenever a thread calls a method, it creates an activation record to hold all of the local variables and parameters of that method, and when several threads call the same method at the same time, each thread gets its own activation record. The threads can neither communicate with one another through the args and locals, nor can they interfere with one another's use of the args and locals.
They can, of course communicate and interfere with each other through any shared objects, including objects that may be referenced by the args or the locals.

Calling a method of a class which extends Thread, from another class

I know this is a bit naive question but I want to understand the basic working principle behind multi-threading in java. Consider the following code and say A is executed in Main thread and it starts execution of another worker thread ,defined in class B. I want to know that can B.func1 called from A and run method of B, be executed in parallel or not?
public class A {
public static void main(String[] args) {
B obj = new B();
obj.start();
obj.func1();
}
}
public class B extends Thread {
public B() {
//constructor
}
public void run() {
while(true) {
//do somethings
}
}
public void func1() {
//do someotherthings
}
}
There is no magic behind a method call. If you call method from a thread, it is called in exactly the same thread. So since obj.func1() is called from main, it will be run in the main thread. It doesn't matter which class it belongs to or whether or not it extends Thread.
The new thread starts by executing run. Everything called from run and so on will be executed in parallel to main.
It's important to understand the difference between a thread and a Thread.
A thread is an independent execution of your code. Often when we talk about how some method or another works we say things like, "It tests the variable x, and if x is less than zero it calls the foobar method..."
Ok, but what is the "it" in that sentence? It is not the method. Methods don't do anything. A method is just a list of instructions, like the list of chores that somebody left for their housemate to perform. The list doesn't do the chores, it's the housemate that does the work (or so we might hope).
The "it" is a thread. Threads are entities in the operating system that execute methods (i.e., they do the chores).
A Thread, on the other hand, is a Java object that your program can use to create and manage new threads. Your program creates a new Thread object by doing:
thread t = new Thread(...);
[Oops! See what I just did? It's not your program, that does the work, it's your program's main thread, or maybe some other thread in your program. It's an easy thing to forget!]
Anyway, it subsequently creates the new thread by calling t.start();
Once you understand all that, then Sergey Tachenov's answer becomes obvious: Calling the methods of a Thread object really is no different from calling methods of any other kind of object.
There are multiple issues with your code. I have corrected them and added one more statement to print Thread Name in func1().
Working code:
public class A {
public static void main(String args[]){
B obj = new B();
obj.start();
obj.func1();
}
}
class B extends Thread{
public B (){
//constructor
}
public void run(){
while(true){
//do somethings
}
}
public void func1 (){
//do someotherthings
System.out.println("Thread name="+Thread.currentThread().getName());
}
}
output:
Thread name=main
Since you are directly calling func1() from main method (A.java) , you will get Thread name = main in output.
If you add same print statement run() method, you will get output as : Thread name=Thread-0

java threading method within object with return value

I am pretty new to using multithreading, but I want to invoke a method asynchronously (in a separate Thread) rather than invoking it synchronously. The basic idea is that I'm creating a socket server with an object in memory, so for each client I will have to run something like object.getStuff() asynchronously.
The two constructs I found were:
having the class implement Runnable and threading this and
declaring a runnable class within a method.
Additionally this method needs a return value- will it be necessary to use Executor and Callable to achieve this? Could someone point me in the right direction for implementing this?
I have tried implement option 2, but this doesn't appear to be processing concurrently:
public class Test {
private ExecutorService exec = Executors.newFixedThreadPool(10);
public Thing getStuff(){
class Getter implements Callable<Thing>{
public Thing call(){
//do collection stuff
return Thing;
}
}
Callable<Thing> callable = new Getter();
Future<Thing> future = exec.submit(callable);
return future.get();
}
}
I am instantiating a single test object for the server and calling getStuff() for each client connection.
Threading Tutorial
The Java tutorial on concurrency has a good section on this. It's at https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html. Essentially, you can either implement Runnable or Callable, or inherit from Thread.
Subclassing Thread
You can write a class, including an anonymous inner class, that extends Thread. Instantiate it, then invoke the start() method.
public class MyThread extends Thread {
public void run() {
System.out.println("This is a thread");
}
public static void main(String[] args) {
MyThread m = new MyThread();
m.start();
}
}
Implementing Runnable
You can write a class that implements Runnable, then wrap an instance in a Thread and invoke start(). Very much like the previous.
public class MyRunnable implements Runnable {
public void run() {
System.out.println("This is a thread");
}
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
(new Thread(r)).start();
}
}
Return Value
Runnable doesn't allow for return values. If you need that, you need to implement Callable instead. Callable looks a lot like Runnable, except you override the call() method instead of the run() method, and you need to give it to an ExecutorService.
public class MyCallable implements Callable<Integer> {
public Integer call() {
System.out.println("A thread using Callable<Integer>");
return 42;
}
public static void main(String[] args) {
MyCallable c = new MyCallable();
Future<Integer> f = Executors.newSingleThreadExecutor().submit(c));
System.out.println("The thread returned: " +
f.get());
}
}
The two constructs I found were 1) having the class implement Runnable and threading 'this' and 2) declaring a runnable class within a method.
Option (2) probably is better. Most programs would be improved if they had more classes, not fewer. Each named entity in a program—each package, class, method, whatever—should have just one responsibility. In your option (1), you are asking the class to do two things.
For your option (2), you don't actually have to declare a whole class. You can either use an anonymous inner class, or if you can go with Java8 all the way, you can use a lambda expression. Google for either one to learn more.
Additionally this method needs a return value.
The classic way, is for the Runnable object to return the value through one of its own fields before the thread terminates. Then the parent thread, can examine the object and get the return value afterward.
Will it be necessary to use Executor and Callable to achieve this?
Necessary? A lot of people think that ExecutorService is a Good Thing.
Sounds like you are creating a server that serves multiple clients. Do these clients continually connect and disconnect? The advantage of using a thread pool (i.e., ThreadPoolExecutor) is that it saves your program from continually creating and destroying threads (e.g., every time a client connects/disconnects). Creating and destroying threads is expensive. If you have a lot of clients connecting and disconnecting, then using a thread pool could make a big difference in the performance of your server.
Creating and managing threads by yourself is generally bad approach.
As you already pointed - use Executors utility class to create executor and submit Callables to it.
public class RunWResult implements Runable{
private volatile ResultType var;
//the thread method
public void run(){
...
//generate a result and save it to var
var = someResult();
//notify waiting threads that a result has been generated
synchronized(this){
notify();
}
}
public ResultType runWithResult(){
//run the thread generating a result
Thread t = new Thread(this);
t.start();
//wait for t to create a result
try{
wait();
}catch(InterruptedException e){}
//return the result
return var;
}
}

Identifying two different threads

I am learning multithreading in java.My doubt is,is there any way two identify two different threads if they have same name below is my code
package com.rajeev.test2;
public class Test11 extends Thread {
public static void main(String[] args) {
System.out.println(Thread.currentThread());
new Test11().start();
new Test12();
}
#Override
public void run() {
Thread.currentThread().setName("ram");
System.out.println(Thread.currentThread());
}
}
class Test12 extends Thread{
static{
new Test12().start();
}
#Override
public void run() {
Thread.currentThread().setName("ram");
System.out.println(Thread.currentThread());
}
}
output
Thread[main,5,main]
Thread[ram,5,main]
Thread[ram,5,main]
I know they are two different threads having same name,so how to know they are different thread without changing name ?
Well you can track the Threads having same name by their ID which will be unique.
Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.
The JVM tracks threads by their ID, not by their name.
long threadId = Thread.currentThread().getId();
You should not use the name of the thread in order to identify a unique thread. The Thread class has a getId() method that returns a long number generated when the thread was created, and that is unique to the thread. Use this in order to know if they are different.
Using getId method
Use getId to identify the uniqueness of the Thread.
Thread id is to be set while creating a new thread. Irrespective of the constructor which will be used.
Thread()
Thread(Runnable, String)
Thread(Runnable)
Thread(String)
Thread(ThreadGroup, Runnable, String, long)
Thread(ThreadGroup, Runnable, String)
Thread(ThreadGroup, Runnable)
Thread(ThreadGroup, String)
all the constructors used init method. In this method has thread id generation.
Also In clone method also has thread id generation.
If Thread gets cloned , new thread id set for new thread reference.
Using equals & Hashcode method
Another way to identify thread uniqueness is using equals and hashcode.
Thread doesnt has same equals and hascode method.
So using hashcode to differentiate thread uniqueness.
You can simply compare the two objects of Test11 and Test12(i.e the threads) using equals operator.
Your example code is completely weird.
Never subclass Thread - there are very rare cases in which this is necessary.
Usually a Thread gets its name from the code that creates it. This makes it easy to give every new thread another distinct name. Do not set the name in the run method.
Please don't start threads in the static constructor of a class.
Probably your example should look simliar to that:
public class ThreadExample {
public static void main(String[] args) {
System.out.println(Thread.currentThread());
new Thread(new PrintThreadNameTask(), "thread-1").start();
new Thread(new PrintThreadNameTask(), "thread-2").start();
}
}
class PrintThreadNameTask implements Runnable {
#Override
public void run() {
System.out.println(Thread.currentThread());
}
}

calling different methods using threads

I want to invoke different methods of class at same time.
I am creating 2 classes: Main- this instantiate object of Function and Function; this extends thread and has 2 methods.
Main.java
package ok;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Welcome to Threading");
Function f1 = new Function();
f1.start();
f1.calling();
f1.calling2();
}
}
Function.java
package ok;
public class Function extends Thread {
public void run() {
// TODO Auto-generated method stub
System.out.println("Run");
for(int y=140;y<170;y++){
System.out.println(y);
}
}
synchronized void calling(){
System.out.println("Let the game begin");
for(int y=40;y<70;y++) {
System.out.println(y);
}
}
synchronized void calling2(){
System.out.println("Let the game begin for me");
for(int y=0;y<40;y++) {
System.out.println(y);
}
}
}
How can I make the methods calling() and calling2() work at the same time?
If I start a thread it goes to run() call and doesn't have any return type. In my program, I need to have return value as a HashMap.
Do I need to create two classes which extends Threads and write logic of calling(), calling2() in run of those two classes?
Please suggest.
Your calling and calling2 methods are synchronized. The very essence of synchronized keyword is to prevent methods from executing concurrently. So in order to invoke both calling and calling2 in parallel you need to drop the synchronized keyword, at least from the method level.
Then, to invoke two methods at the same time, one Thread object is enough - one invocation can be executed in new thread, the other in the "current" thread, like this:
Thread thread = new MyThread();
thread.start(); // body of run() invoked in a new thread
thread.run(); // body of run() invoked in this thread, concurrently
It's better practice to produce separate Runnable objects for such use-cases, though. This has several advantages over the aformentioned approach:
it's more flexible - as the action is decoupled from the execution and encapsulated in a separate object, it becomes more like "data". If you ever feel the need to change computation strategy - e.g. use thread pool - it's trivial to do so with Runnable tasks. Not so with Thread extensions.
it's conceptually more sound, as subclassing a Thread suggests specializing its behaviour, while Runnables are more like "task containers" - favor composition over inheritance.
it's symmetric - no computation is treated differently, it's trivial to change e.g. which one executes where
Last, you seem to want to return something from your methods. For this, you might use a Future - a java concurrency utility class, representing asynchronous computation. In addition to Runnable advantages, it can return a value and offers features like cancellation and state querying.
You have to have the calls for running the methods inside your run() method.
Then you can just call the start() method and both methods will run. But that does not really solve the problem. What you need to do is create two threads and have each of them run their respective threads.

Categories