Why does one thread stop the other thread from running? - java

I was going to use threads for each sound in a game engine I'm making. The problem is, whenever I make a new thread that has a while(true) statement, the other thread stops running.
I made a class to test this, and it only prints "goodbye", not "hello". I was wondering how to make the two threads run at the same time.
public class testor {
public static void main(String args[]){
testor test=new testor();
test.runTest();
}
class threadTest implements Runnable{
#Override
public void run() {
while(true){
System.out.println("goodbye");
}
}
}
public void runTest(){
threadTest test=new threadTest();
test.run();
while(true){
System.out.println("hello");
}
}
}

Since you are doing test.run(); you are only calling the method of that class but not starting the thread.
So in order to answer your question: there is no such a thread stopping the other thread from running? because you have only one Thread that is looping for ever and printing the message System.out.println("goodbye");
If that method is not looping for ever, it would return to the runTest method and then you would see the System.out.println("hello");
Summary:
For starting a Thread use the Thread::start method and not the run.

Using (new ThreadTest()).run() does not start a new Thread, but just invokes the run() method in the current thread.
To run the code in a separate thread do:
(new Thread(new ThreadTest())).start();

That's because you're not creating a new thread. Just naming a class something containing "thread" will not make it a thread, and a Runnable is no thread - it's a class like any other, with no special semantics or behaviour.
It's only special in that you can pass it to a Thread for execution.
public class Testor {
public static void main(String args[]){
Testor test=new Testor();
test.runTest();
}
class MyRunnable implements Runnable{
#Override
public void run() {
while(true){
System.out.println("goodbye");
}
}
}
public void runTest(){
Thread testThread = new Thread(new MyRunnable());
testThread.start();
while(true){
System.out.println("hello");
}
}
}
You should probably also adhere to the Java coding standards regarding your class and variable names if you do not want your code to look like an alien when combined with most other existing Java code.
Additionally, multithreading is more than just being able to start a new thread. You should also read about synchronisation issues - it's more complicated to do correctly than you might imagine.

Your run method contains an infinite loop.
The runTest() method creates the thread which means you'll have 2 execution stacks the main stack, and the runnable threadTest stack.
since you're running the thread method first that contains an infinite loop, you'll always get the output "good Bye".
Remove the infinite loop from run() method.

Related

How this below program is executing as thread reference is not passed

I am not able to understand the behavior of this below program ,well as i can see that there is no thread reference is there in which we can pass the myThread reference but still the program is executing please advise is it the main thread which is executing this program
class MyThread extends Thread
{
public static void main(String [] args)
{
MyThread t = new MyThread();
t.start();
System.out.print("one. ");
System.out.print("two. ");
}
public void run()
{
System.out.print("Thread ");
}
}
the output is
one. two. Thread
This program consists of two threads.
The main() thread which is started when you start the program
The MyThread thread which you start from main()
This call:
t.start();
...will start a 2nd thread, which will run the code in the MyThread class's run method.
Because when you call t.start() , the run() method (you override) is executed,
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
The start() method :
- Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
I've always found the practice of letting your Main class extend something (in example code) dubious at best as it is unclear for beginners that when the main method is called there actually is no instance yet of the Main class (in this case the MyThread class).
So I've rewritten the example to make it more clear as to what happens:
public class Main
{
public static void main(String [] args)
{
// main gets called when starting your program (which is a thread created by the JVM for free)
MyThread t = new MyThread(); // You create a new Thread here
t.start(); // You start the thread
System.out.print("one. "); // In the mean time, the main thread keeps running here
System.out.print("two. ");
}
public static class MyThread extends Thread {
#Override
public void run()
{
System.out.print("Thread ");
}
}
}

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

How method preference work in java?

I just want to understand how below code snippet work ?
class AnnaThread extends Thread {
public static void main(String args[]){
Thread t = new AnnaThread();
t.start();
}
public void run(){
System.out.println("Anna is here");
}
public void start(){
System.out.println("Rocky is here");
}
}
Output - Rocky is here
There's not much to explain.
You override start() with code that prints Rocky is here
then you call start() which prints Rocky is here.
(the run method is never involved)
People often confuse the purpose of start and run. See for instance this question:
Why we call Thread.start() method which in turns calls run method?
The rules are simple:
Thread.run is an ordinary method (no magic)
Thread.start contains some magic because it spawns a separate thread (and lets that thread invoke run).
If you override Thread.start with your own method, then there's no magic left anywhere.
what you have here is a Java class which extends the Thread class (http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html)
class AnnaThread extends Thread {
then in your main method you create a new instance of the class which is a Thread (since the class extends the Thread)
public static void main(String args[]){
Thread t = new AnnaThread();
then you call the method start which follows bellow
t.start();
which prints
System.out.println("Rocky is here");
you could as well call the other method if you add the following line in your code
t.run();
in which case the method run would be executed which would print
System.out.println("Anna is here");

Why Thread.start() is needed? [duplicate]

This question already has answers here:
Please explain the output from Thread run() and start() methods
(4 answers)
Closed 8 years ago.
I was working on Threads when a question struck to my mind..If we can directly call run() method with the object of a class like any ordinary method then why do we need to call Thread.start() to call run() method..I tried both the methods as shown and got same result with both of them
First attempt by calling run() method directly
class Abc extends Thread
{
public void run()
{
for(int i=0;i<5;i++)
{
System.out.println("Abc");
}
try
{
Thread.sleep(100);
}catch(Exception e)
{
System.out.println("Error : "+ e);
}
}
}
class Xyz extends Thread
{
public void run()
{
try
{
for(int i=0;i<5;i++)
{
System.out.println("Xyz");
}
Thread.sleep(100);
}catch(Exception e)
{
System.out.println("Error : "+ e);
}
}
}
public class ThreadDemo
{
public static void main(String[] args)
{
Abc ob=new Abc();
Xyz oc=new Xyz();
ob.run();
oc.run();
}
}
Second attempt by calling Thread.start()
public class ThreadDemo
{
public static void main(String[] args)
{
Abc ob=new Abc();
Xyz oc=new Xyz();
Thread t1,t2;
t1=new Thread(ob);
t2=new Thread(oc);
t1.start();
t2.start();
}
}
If you call run() directly, the code gets executed in the calling thread. By calling start(), a new Thread is created and executed in parallel.
If you directly call run(), then all the work will be done on the main thread.
By using Thread.start, then it will executed on a new thread other than the main thread ;)
To observe what the difference is, increase your sleep calls to something longer like 10 seconds. This will make it obvious that you need Thread.start to avoid the first task waiting on the second.
In the case where you use Thread.start, you will see that output of both threads appears immediately.
In the case where you use run, you will see that the output of the first appears, then a 10 second delay, then the output of the second.
If you call run() method directly then code will run inline. To run the code in separate thread it is necessary to call Thread.start().
When you call start() method on thread reference it create span entirely context area. Then thread will have independent stack from where you are calling. More over start() invokes OS native thread to start it in separate memory context.
While run() method invocation considered as simple method call, and you won't have benefit of concurrency as its executing is current stack.

Java: Thread.sleep() inside while loop not working

Alright, I'm new to threading, so my question might be pretty dumb. But what I want to ask is, I have this class, let's say its name is MyClass.java. And then inside one of its methods is callThread(), which I want to print something out, sleep, and return control to MyClass.java's method. How do I do that?
Currently, my code goes something like this:
class MyClass {
void method()
{
MyThread thread = new MyThread();
thread.run();
// do some other stuff here...
}
}
And then, this will be the MyThread:
class MyThread implements Runnable {
public void run()
{
while (true)
{
System.out.println("hi");
this.sleep(1000);
}
}
}
I was hoping that MyThread would print "hi", pass back control to MyClass, and then print "hi" again one second later. Instead, MyThread freezes up my entire program so having it in there doesn't work at all...
Is there any way around this?
You should be callig thread.start()
More on that in the manual: Defining and Starting a Thread
You must have to call start() method of Thread class.
MyThread thread = new MyThread();
Thread th=new Thread(thread);
th.start();
sleep() is an instance method of Thread class and MyThread class is not a thread (It's a runnable) so you need to use Thread.currentThread().sleep() method.
while (true)
{
System.out.println("hi");
try{
Thread.currentThread().sleep(1000);
}catch(Exception ex){ }
}
Read this tutorial for more info on thread.

Categories