In real time Java one can create a real time thread and run it via the following methods:
RealtimeThread rt = new RealtimeThread(){
public void run(){
/*do work*/
}
};
rt.start();
RealtimeThread rt2 = new RealtimeThread();
rt2.start();
RealtimeThread rt3 = new RTThread();
rt3.start();
where RTThread is a class which extends RealtimeThread. But clearly the above approaches does not work when it comes to main. So is there a way to do it? My motivation for this is that I want only 2 real time threads to run. If I start two real time threads within main, won't there be a total of 3 threads?
if the RealtimeThreads are not deamon threads you can let the main thread finish and keep everything running inside the RealtimeThreads
public class BootStrap extends Runnable{
public static void main(String[] args){
new RealtimeThread(new BootStrap()).start();
//main finishes running and stops
}
public void run(){
//...
}
}
If I start two real time threads within main, won't there be a total of 3 threads?
No. If you start two threads, then return / "fall off the edge" of the main method, you'll have two threads running.
Aren't all threads RealTimeThreads in RTJ? including the main thread?
Related
Code:
public class ThreadTest {
public static void main(String[] args) {
MyImlementThread mit = new MyImlementThread();
Thread t = new Thread(mit);
t.start();
t = new Thread(mit);
t.start();
}
}
// MyImlementThread
class MyImlementThread implements Runnable {
public void run() {
System.out.println("This is implemented run() method");
}
}
/*
Output
This is implemented run() method
This is implemented run() method
*/
What happens here is the main thread starts two threads and exits. Each of the new threads writes a message to stdout, then ends. At that point since all the non-daemon threads have finished the JVM exits.
The posted code is confusing on account of it defining a Runnable but giving it a name ending in Thread.
A Thread object relates to an os-level thread, calling start on a Thread makes the code in the run method of the passed-in Runnable execute run on a separate thread from the one that called start.
The Runnable defines a task but doesn't specify how it runs. It could be passed into a specific Thread's constructor or submitted to an Executor or run by the current thread.
In this case the Runnable declared has no state, no instance variables are declared. Here two threads can execute the same Runnable without a conflict because there is no shared state. The printstream that writes to the console is synchronized, so the lines written by the threads each get written one at a time and don't get jumbled together.
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.
Here is the Example Code:
public class HelloRunnable implements Runnable {
#Override
public void run() {
System.out.println("Run Entered");
}
public static void main(String args[]) {
Thread obj=new Thread(new HelloRunnable());
obj.start();
System.out.println("ABC");
}
}
Output:
ABC
Run Entered
Why ABC before the run()'s code?
Even I create 3 threads. But still ABC print first;
obj.start();
obj1.start();
obj2.start();
Really I tried to search about this, but unable to find the query for this.
Simply because the HelloRunnable.run method is executed in another thread than the one printing ABC. They execute concurrently, that's the point of threads. Therefore, any of the two may access a certain resource, like the stdout, before the other.
When you call obj.start(), internally it spawns a new thread. So at that stage, you have 2 threads in your process, One is main thread, and one is new thread.
Each thread needs cpu to execute, and that's driven by cpu scheduling queue. If main thread hold the cpu, then out put will be what you saw. If context switch happens just after the statement obj.start();then cpu is given to new thread, Then you will see the thread output first and then the main output.
So the behavior is undeterministic as you can never predict that after which statement the context switch will happen.
Also what you see in the code is not what gets executed at the cpu. At the cpu assembly is executed. So even if you say that you were executing obj.start(), but you can never say on which assembly instruction you really were when context switch happened.
Would be reverse or like this. You started a "Thread". You are running on the main thread. So you have two independent running code. How do you guarantee that one will finish its work before the other ?
Try to sleep main thread after starting other threads. With
Thread.sleep(2000);
Then other threads would finish their works. You can see that ABC printed last.
public class HelloRunnable implements Runnable {
#Override
public void run() {
System.out.println("Run Entered");
}
public static void main(String args[]) {
Thread obj=new Thread(new HelloRunnable());
obj.start();
try{
Thread.sleep(2000);
}
catch(Exception e){}
System.out.println("ABC");
}
}
They are parallel works so you don't have a guarantee that ABC printed lastly or firstly. Depends on the machine CPU, works you have.
I have a MainClass, a Worker class and a Supervisor class. In MainClass i create 10 Worker classes and a Supervisor class that run in separate threads.
class MainClass {
public static void main(String args[]) {
for (int i=0; i<10 ;i++) {
Thread t = new Thread( new Worker());
t.start();
}
(new Thread(new Supervisor()).start();
}
.
class Worker extends Thread {
public void run() {
while(true) {
if(some_condition) {
//do stuff
} else {
// pause thread execution for undefined time.
}
}
}
}
.
class Supervisor extends Thread {
public void run() {
while(true) {
if(some_condition) {
// restart Workers thread that are paused.
}
// do other stuff
}
}
}
I don't know how to implement this, cause the conditions in every thread are independent from each other so i don't need to synchronize, so i can't use wait-notify.
I don't know how to implement this, cause the conditions in every thread are independent from each other so i don't need to synchronize, so i can't use wait-notify.
Sure you can.
The subtlety here is that presumably Supervisor doesn't actually know whether worker threads are really paused. (If it does, then the conditions are not independent.)
Since Supervisor doesn't know whether the threads are actually paused (by assumption), you have to design what you want to happen if it tries to unpause an already-unpaused thread.
a) Should an unpause do nothing?
b) Or should it immediately unpause the next time a worker tries to pause itself?
If the answer is (b), then you have to worry about thread safety. If the answer is (a), then you don't (unless you have some other data to pass between threads!)
Either way, you can still use wait and notify.
As per my understanding u want to create separate thread pools which consist of 10 workers or number as per your requirement.
As far as pools are concerned you can check for ThreadPoolExecutor in java.util.concurrent api. Internally ThreadPoolexecutor also creates worker Threads for running tasks.
Try reading ThreadPoolExecutor it might help you or please elaborate your question whats your ultimate objective you wish to achieve by this problem.