"this" is used to refer to the members of the current class. I was trying a program in java using multithreading.
this => object of the current class where it is referred
The program is
class Thread_child implements Runnable{
Thread t;
Thread_child()
{
t = new Thread(this,"DemoThread");
System.out.println("ChildThread:"+t);
t.start();
}
public void run(){
char a[] = {'A','B','C','D','E','F','G','H','I','J'};
try{
for(int i=0;i<10;i++){
System.out.println("ChildThread:"+i+"\t char :"+a[i]);
Thread.sleep(5000);
}
}
catch(InterruptedException e){
System.out.println("ChildThread Interrupted");
}
System.out.println("Exiting from the Child Thread!");
}
}
class Thread_eg{
public static void main(String args[]){
new Thread_child();
try{
for(int i=1;i<=10;i++){
System.out.println("MainThread:"+i);
Thread.sleep(3000);
}
}
catch(InterruptedException e){
System.out.println("MainThread Interrupted");
}
System.out.println("Exiting from the Main Thread!");
}
}
What does this Thread() constructor do . why do we need to pass 'this' as a parameter to it. I tried to run it without giving the parameter but the child threads were not run.only the mainthread was printed . when i replaced the thread constructor with the parameter it ran the child threads. why is that so?
Have a look at the documentation for that constructor, and all should become clear. Pay particular attention to the part that states
If the target argument is not null, the run method of the target is called when this thread is started. If the target argument is null, this thread's run method is called when this thread is started.
(The underlying issue is that a Thread is just a thread, and doesn't inherently do anything. You need to tell it what to execute.)
Because this is the Runnable object (Thread_child) whose run() method gets called.
There are two ways of implementing a Thread. One is create a class that extends Thread class and this class runs as a thread in VM.
MyThread mt = new MyThread();
mt.start();
The start will result in execution of run method that was overridden from Thread.
In case you could not extend to Thread, you can implement Runnable which makes you implement run method. Now to run this class you need to pass an object of it to Thread.
MyRunnable mr = new MyRunnable();
Thread t = new Thread(mr); // telling the thread what needs to be execute through run method
t.start();
In your code since you are starting thread in constructor, you have passed this instead my mr in above example. Basically you need to tell Thread what it needs to do via run method.
This is how run of Thread looks like:
public void run() {
if (target != null) { //target is nothing but a Runnable.
target.run();
}
}
Related
i am new to multithreading and trying to clear my basics.
public class SleepExample extends Thread {
private int counter = 0;
#Override
public void run() {
try {
counter++;
System.out.println("Value of counter "+counter);
System.out.println("Thread going in sleep "+Thread.currentThread().getName());
Thread.currentThread().run();
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
System.out.println("Thread out of sleep "+Thread.currentThread().getName());
}
public static void main(String[] args) {
new SleepExample().start();
new SleepExample().start();
Test test = new Test();
Thread t = new Thread(test);
t.start();
}
}
//another class implementing runnable
public class Test implements Runnable {
#Override
public void run() {
System.out.println("In Test runnable method");
}
}
When i run this code, my run method of SleepExample recursively call itself after below line
Thread.currentThread().run();
for thread belonging to SleepExample (Thread -0, Thread -1) and
it goes to run method of Test class for thread t.
I am unable to understand the usage of Thread.currentThread().run();
P.S. - I read its java doc and so i have implemented a runnable
I am unable to understand the usage of Thread.currentThread().run();
You are not supposed to call it directly. From Thread.start() You are supposed to use start() to call run() and that is it.
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
You are already running in the run() so you should only call this if you can say why you are doing it, even then it will look like a bug or be plain confusing and I would suggest you use a loop instead.
When i run this code, my run method of SleepExample recursively call itself after below line
You have a method calling itself, so you should expect that to happen. There is nothing special to Thread in this regard. It is like any other recursive call in a method.
package com.nacre.test7;
public class TestDaemon {
public static void main(String[] args) throws InterruptedException {
MyDaemon dt=new MyDaemon();
if(dt.isDaemon()){
System.out.println(dt+"is demon thread");
Thread.sleep(1000);
System.out.println(" main thread is ending.");
}
}
}
package com.nacre.test7;
public class MyDaemon implements Runnable{
Thread thrd;
MyDaemon() {
thrd=new Thread(this);
thrd.setDaemon(true);
thrd.start();
}
public boolean isDaemon(){
return thrd.isDaemon();
}
public void run() {
try { while(true) {
System.out.print(".");
//Thread.sleep(100);
}
} catch(Exception exc) {
System.out.println("MyDaemon interrupted.");
}
}
}
In the above 2 class I have given breakpoint to each line in the program.I started debugging in eclipse editor and what I saw the control flow is ...........coming back to this below code after executing thrd.start() method of MyDaemon class
if(dt.isDaemon()){
System.out.println(dt+"is demon thread");
Thread.sleep(1000);
System.out.println(" main thread is ending.");
}
and noway the control is going to this below part
public void run() {
try { while(true) {
System.out.print(".");
Thread.sleep(100);
}
} catch(Exception exc) {
System.out.println("MyDaemon interrupted.");
}
What I knew is that when start() method is called , concurrently jvm calls run method by creating a new thread , my doubt is that why I am unable to see the execution of the run method while debugging
and how I am getting the following output
com.nacre.test7.MyDaemon#152b6651is demon thread
.......... main thread is ending.
Java Virtual Machine.
When you create Thread object and call start() on it gives the JVM a special instruction to create java thread,Here JVMdoes some deep magic that we cannot do in normal Java code. Via native calls it creates a new thread and causes the new thread to call the run() method.
According to Thread#start
Calling start() causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
Answer to
how I am getting the following output
com.nacre.test7.MyDaemon#152b6651is demon thread .......... main thread is ending.
The program is behaving perfectly fine. You cannot accept the main thread to be alive if the only thread it starts is a Daemon thread. Please read the source code / java doc of the Thread class.
Moreover, to your other question my doubt is that why I am unable to see the execution of the run method while debugging and
The run method execution is shown in the debug mode as below:
who is calling to the run() method?
The thrd.start() call in the MyDaemon constructor is causing it to happen.
In MyDaemon you instantiate a Thread object and pass it this as an argument. When a Thread object is started, it calls its run() method, and the default behaviour of the Thread.run() object is to call run() on its Runnable ... if one was supplied.
So:
the MyDaemon constructor creates a Thread object
the MyDaemon constructor calls thrd.start()
thrd.start() starts the new thread with a new stack
the new thread calls thrd.run()
thrd.run() calls run() on the MyObject instance
Note that steps 1 through 3 happen on the parent thread, and steps 4 through 5 happen on the child thread, either before or after the start() call returns in the parent thread.
I'm new to threads. I wanted to create some simple function working separately from main thread. But it doesn't seem to work. I'd just like to create new thread and do some stuff there independently of what's happening on main thread. This code may look weird but I don't have much experience with threading so far. Could you explain me what's wrong with this?
public static void main(String args[]){
test z=new test();
z.setBackground(Color.white);
frame=new JFrame();
frame.setSize(500,500);
frame.add(z);
frame.addKeyListener(z);
frame.setVisible(true);
one=new Thread(){
public void run() {
one.start();
try{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
} catch(InterruptedException v){System.out.println(v);}
}
};
}
You are calling the one.start() method in the run method of your Thread. But the run method will only be called when a thread is already started. Do this instead:
one = new Thread() {
public void run() {
try {
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
} catch(InterruptedException v) {
System.out.println(v);
}
}
};
one.start();
You can do like:
Thread t1 = new Thread(new Runnable() {
public void run()
{
// code goes here.
}});
t1.start();
The goal was to write code to call start() and join() in one place.
Parameter anonymous class is an anonymous function. new Thread(() ->{})
new Thread(() ->{
System.out.println("Does it work?");
Thread.sleep(1000);
System.out.println("Nope, it doesnt...again.");
}){{start();}}.join();
In the body of an anonymous class has instance-block that calls start().
The result is a new instance of class Thread, which is called join().
You need to do two things:
Start the thread
Wait for the thread to finish (die) before proceeding
ie
one.start();
one.join();
If you don't start() it, nothing will happen - creating a Thread doesn't execute it.
If you don't join) it, your main thread may finish and exit and the whole program exit before the other thread has been scheduled to execute. It's indeterminate whether it runs or not if you don't join it. The new thread may usually run, but may sometimes not run. Better to be certain.
Since a new question has just been closed against this: you shouldn't create Thread objects yourself. Here's another way to do it:
public void method() {
Executors.newSingleThreadExecutor().submit(() -> {
// yourCode
});
}
You should probably retain the executor service between calls though.
There are several ways to create a thread
by extending Thread class >5
by implementing Runnable interface - > 5
by using ExecutorService inteface - >=8
If you want more Thread to be created, in above case you have to repeat the code inside run method or at least repeat calling some method inside.
Try this, which will help you to call as many times you needed.
It will be helpful when you need to execute your run more then once and from many place.
class A extends Thread {
public void run() {
//Code you want to get executed seperately then main thread.
}
}
Main class
A obj1 = new A();
obj1.start();
A obj2 = new A();
obj2.start();
run() method is called by start(). That happens automatically. You just need to call start(). For a complete tutorial on creating and calling threads see my blog http://preciselyconcise.com/java/concurrency/a_concurrency.php
A simpler way can be :
new Thread(YourSampleClass).start();
Please try this. You will understand all perfectly after you will take a look on my solution.
There are only 2 ways of creating threads in java
with implements Runnable
class One implements Runnable {
#Override
public void run() {
System.out.println("Running thread 1 ... ");
}
with extends Thread
class Two extends Thread {
#Override
public void run() {
System.out.println("Running thread 2 ... ");
}
Your MAIN class here
public class ExampleMain {
public static void main(String[] args) {
One demo1 = new One();
Thread t1 = new Thread(demo1);
t1.start();
Two demo2 = new Two();
Thread t2 = new Thread(demo2);
t2.start();
}
}
When i start some thread in my program, everything else is stopped.
This is my Thread code...
static Thread b1 = new Thread(new Builders());
b1.run();
System.out.println("done");
This is the class Builders.
public class Builders implements Runnable {
static boolean busy=false;
Random r = new Random();
public void run() {
try{
busy=true;
System.out.println("ready");
Thread.sleep(9999);
busy=false;
System.out.println("done");
}
catch(Exception e){
}
}
}
When I run the program , the thread is started and the program wait for the end of the thread. I thought the main point of the threads is that the code can run simultaneously. Could someone please help me understand what I'm doing wrong.
That's because threads are started with start(), not run(), which simply calls the run method on the current thread. So it should be:
static Thread b1 = new Thread(new Builders());
b1.start();
System.out.println("done");
This is because you are not starting a thread - instead, you are executing thread's code synchronously by calling run(); you need to call start() instead.
Better yet, you should use executors.
You need to call the start() method. The internal code of Thread will start a new operating system thread that calls your run() method. By calling run() yourself, you're skipping the thread-allocation code, and just running it in your current Thread.
I have a method and a thread which I'd like to run in the following order: First the method should do something with an object, and then the thread should do something with the object. They share the same object. I have to synchronize them, but I am just meeting with Threads. How can I do that?
private synchronized method()
{
//do something with an object (a field)
}
Runnable ObjectUpdater = new Runnable()
{
//do something with the object after the method has finished
}
My code, that somehow manages to freeze my Main thread (where the method is)
My thread code:
private Runnable something = new Runnable(){
synchronized (this){
while (flag == false)
{ try {wait();)
catch (IntExc ie) {e.printStackTrace...}
}
//here it does its thing
}
setFlag(false);
}
My method code (part of the main thread)
private void Method()
{
//do its thing
setFlag(true);
notifyAll();
}
To me that is simple questions
" you said that I do not know which is
going to access the object first - the
separate ObjectUpdater thread, or the
main thread (with the method). If the
separate thread accesses it before the
main thread, that is bad and I don't
want this to happen"
if you want the main thread method to call first then the objectUpdater thread , have a flag to know whether the method is visited first by main thread ,if it is updater then call wait to this thread , once main finishes it call notify which will run separator thread,
to know which thread is main thread or updater thread , set a name to the thread while creating it. and get the name as Thread.currentThread().getName().
Use the Semaphore class to allow access to the object.
public class Main
{
public static void main (String[] args) {
final Obj obj = new Obj();
final Semaphore semaphore = new Semaphore(0);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
semaphore.acquire();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return;
}
obj.doSomething();
}
});
t.setName("test");
t.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
obj.doSomething();
semaphore.release();
}
}
class Obj {
public void doSomething() {
System.out.println("something done by " + Thread.currentThread());
}
}
Apart from synchronizing on the object, you could call the method as first statement in the new thread, or you could start the new thread at the end of the method.
It is hard to say what is the best approach in your case, maybe you can give us some more details on the how and what?
Update
In answer to your code (for some reason I cannot add another comment...)
Is the method called from a synchronized(this) block? If not the notifyAll() should be in a synchronized block. Also, can you update the code to show where/how your main thread interacts with the method and the object?
I think better approach would be to call the method using which you want to perform something with an object, and then declare the thread which would do something with an object.