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");
Related
I've been fiddling with creating a thread on which the rendering runs, and I've come across this way of implementing it:
Class Main implements Runnable {
private Thread thread;
private boolean running = false;
public void start() {
running = true;
thread = new Thread(this, "renderingThread")
thread.start(); //calls run()
}
public void run() {
init(); //init glfw + create window
while(running) {
update();
render();
}
}
public static void main(String[] args) {
new Main().start()
}
Note that only the sections of the code that are related to threads have been included.
Now, the program flow looks something like this (correct me if I'm wrong): Construct new object of type/class Main (hence, reserve a place on the heap). Then, the start() method of object of type Main is called. running boolean is set to true. Then, a new thread is created via constructor Thread (Runnable target, String name) - in my case, the first parameter is this keyword, meaning that the reference of the object of type Main is passed as the first parameter (since the method has been called by the object of type Main). Then, the next line is what fiddles me the most. The thread reference calls the method start(), but it somehow refers to the run() method. How?
I'd be very thankful for a thorough explanation of how start() method for a thread object can refer to the run() method.
You create a new Thread with a Runnable target of this (the instance of Main class). Main implements Runnable means the method run() is overridden. The Thread class itself implements Runnable.
When you start the thread with the configuration above, the method start() causes the thread to begin execution; the Java Virtual Machine then calls the Thread object's run() method. It's said in the documentation. If you are curious, see the source code of the java.lang.Thread.
You can achieve the same effect with a simpler approach:
public class Main implements Runnable {
#Override
public void run() {
System.out.println("New thread");
}
public static void main(String[] args) {
new Thread(new Main()).start();
System.out.println("Main thread");
}
}
Take a look at the JavaDoc (https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#start--)
When start() is called on the Thread Object it creates a new Thread and calls the run() method on that thread.
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 ");
}
}
}
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
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.
I am beginner in java. I have been studying multithreading. I want to create two threads and these two threads must run separate methods concurrently. Here these threads should call sum and diff method and run simultaneously. But I am getting an error, that method should be of thread type. How to achieve it.
class Demo implements Runnable
{
void sum()
{
//Some lines of code
}
void diff()
{
//Some lines of code
}
public void run ()
{
System.out.println("Inside run");
}
}
class Test
{
public static void main (String []args){
Demo o = new Demo ();
Demo o1 = new Demo ();
Thread th = new Thread (o);
Thread th1= new Thread(o1);
th.start();
th1.start();
o.th.sum(); // getting error here
o1.th1.diff(); // getting error here
}
}
First of all you have a compilation error because you're trying to reference the variable th as a field on an object of type Demo. th is not a field, but rather a local variable and can be referenced directly (i.e. without the o. prefix). Second, sum() and diff() cannot be called against an instance of Thread as those methods are not defined by thread, but rather by your own Demo class.
All that being said, these compilation problems aren't even the root issue for this code. Based on your code it seems you have some fundamental misunderstandings about the syntax and structure of Java programs so it might benefit you to go through some entry-level tutorials before trying to tackle concurrent programming. But, for the sake of completeness here is a brief explanation of what you need to do in order to make your program work.
When you call Thread.start() it's going to fork a thread and call the run() method of the Runnable you passed into that thread object's constructor.
In order to call the two different methods you need to create two different classes that implement runnable and put the two method implementations in each of their run methods.
Example:
public class Sum implements Runnable {
public void run() {
//Add up your numbers
}
}
public class Diff implements Runnable {
public void run() {
//Subtract numbers
}
}
public class Test {
public static void main(String[] args) {
Thread sumThread = new Thread(new Sum());
Thread diffThread = new Thread(new Diff());
sumThread.start();
diffThread.start();
}
}
Assuming that you are getting a compilation error, the statement o.th.sum() is incorrect.
The statement o.th will cause the compiler to look for a public static class level field in the Demo class with the name th. Since there is no such field in Demo class, you get an error.
You are getting this error because you are trying to access the Thread's local variable using the object of the Demo class and you can't call the method directly if you want's it to run it in a separate thread. A new thread will spawn only when you call start() method on thread class and then it will execute the code in run() method.
As per your requirement to create two threads and these two threads must run separate methods concurrently, following code should work.
class Demo implements Runnable
{
public void run ()
{
//sum() method code
}
}
class Demo1 implements Runnable
{
public void run ()
{
//diff() method code
}
}
class Test
{
public static void main (String []args){
Demo o = new Demo ();
Demo1 o1 = new Demo1 ();
Thread th = new Thread (o);
Thread th1= new Thread(o1);
th.start();
th1.start();
}
}