I am a beginner here and started learning java programming.
I wrote a program to try threading. In one class i wrote a program to display numbers from one to 100 and in another class to display number from 999 to 100. Now in the the main i have created an object reference for both the class(r1,r2)) and created a object for thread and passed(r1,r2-object reference of my class) them as a parameter. Now the output i get is not as expected in some way i feel my second thread is not getting executed. I am not sure if there is anything wrong with my logic or the program. Any help/advice would be appreciated. My code below for reference.
Class 1:
public class Run implements Runnable {
#Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
Logger.getLogger(Run.class.getName()).log(Level.SEVERE, "...", ex);
}
System.out.println(i);
}
}
}
Class 2:
public class Run2 extends Thread {
public void run2() {
for(int i=999;i>0;i--){
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(Run2.class.getName()).log(Level.SEVERE, "....", ex);
}
System.out.println(i);
}
}
}
Main class:
public class Threading {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Run r= new Run();
Thread t1=new Thread(r);
t1.start();
Run2 r2=new Run2();
Thread t2=new Thread(r2);
t2.start();
}
}
Rename Run2's method run2 to run. You're subclassing Thread, so you get a run method that doesn't do anything (actually it checks to see if it was passed in a target runnable, in which case it calls run on the target, but since the target is null it does nothing), and that's what's getting run.
Make a habit of implementing Runnable instead of extending Thread, and use the #Override annotation to catch mistakes where you think you're overriding something but you're not.
Your class Run2's method should be named run and not run2.
Related
This question already has answers here:
How to start anonymous thread class
(9 answers)
Closed 5 years ago.
This thread does not execute when I run the program. I'm wondering if there's something wrong with the code.
public static void writeToFileAsync(final String saveState, final String fileName) {
new Thread() {
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
}
start();
}
};
}
Also, why does NetBeans want me to put that semicolon next to the second curly brace after the start() call?
Start a thread
Your thread will only start if you call the start method explicitly. Here is the documentation Thread#start. The start method will then internally invoke the run method of your Thread.
Your code could then look like this:
public static void writeToFileAsync(final String saveState, final String fileName) {
// Create the thread
Thread fileWriter = new Thread() {
#Override
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
// Do nothing
}
}
};
// Start the thread
fileWriter.start();
}
And you probably want to remove the start(); call inside your run method.
Semicolon
You need the ; after the Thread creation because you are using an assignment:
Thread fileWriter = new Thread() { ... };
The concept you are using here is called anonymous class. Basically it is the same as if creating a new class like:
public class FileWriter extends Thread {
#Override
public void run() {
...
}
}
And then using it like:
Thread fileWriter = new FileWriter();
However an important difference is that your anonymous class has access to your local variables (the scope of that method). And that it is anonymous, so it's like a small single-time usage class.
Your call to the start method cannot be inside the body of your thread. You can do this:
new Thread() {
public void run() {
try {
writeToFile(saveState, fileName);
} catch (IOException ex) {
}
}
}.start(); // call the start method outside the body of you thread.
And about the semicolon, you are creating an Anonymous Class and that is its syntax:
Because an anonymous class definition is an expression, it must be
part of a statement... (This explains why there is a semicolon after
the closing brace.)
A thread simply works this way. Below is a piece of code where a thread is created as an anonymous inner type where the run method is overrided. Then by calling the start method , it automatically called the overrided run method.
public class ThreadTest {
Thread t = new Thread(){
public void run() {
System.out.println("thread is running");
};
};
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
threadTest.t.start();
}
}
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.
i'm wondering what the code would look like in order to have a program which creates a loop on start. This loop then creates several, thread objects all on their own threads so their all running at the same time, and they all run the same code. Is there a way to do this? as in for example we make 2 threads, they never stop looping and one is always prinintg "thread 1" and 1 is always printing "thread 2" at the same time. This is what i'm wondering. Thanks in advance!
class MyTask implements Runnable {
public static id = 0;
public MyTask(){
id++;
}
public void run(){
while(true){
System.out.print("Thread " + id);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Generator{
Public static void main(String[] args){
Runnable[] myTasks = new Runnable[2];
myTasks[0] = new MyTask();
myTasks[1] = new MyTask();
for(Runnable r: myTasks){
Thread t = new Thread(r);
t.start();
}
}
}
I didn't compile it. but this is how you are going to do.
When you run class Generator, two Threads will start, and they will print Thread 1. and thread 2 once every one second forever.
How do we implement efficient exception handling when using threads.
I have a main program which creates 3 threads. How do we handle the exceptions for the exceptions thrown during the execution of thread?
Can we use the try/catch block or uncaughtexception. If so, can you please share some samples.
public class MyThreadTest {
public static void main(String[] args) {
Thread newThread = new Thread(new ThreadWithException());
// Add the handler to the thread object
newThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler(){
#Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("ERROR! An exception occurred in " + t.getName() + ". Cause: " + e.getMessage());
}
});
newThread.start();
}
}
/**
* This thread throws a custom exception in its run method.
*/
class ThreadWithException implements Runnable {
#Override
public void run() {
throw new RuntimeException("Application Specific Exception!!");
}
}
Either you can use:
Thread#setUncaughtExceptionHandler to specify some code that is run when an exception is thrown (outside of normal program flow), or:
ExecutorService#invokeAll to run all of your blocks, and inspect the returned list for Future#get()'s throwing of ExecutionException. Another option is CompletionService, but this is slightly harder to use for such a simple case.
You can use try / catch block strategy:
Thread t = new Thread() {
#Override
public void run() {
try {
//..thread code
} catch (Exception e) {
}
}
};
It is easy to implement but in case of exception main thread of your application will never know what happened inside of child thread.
Better method would be to spawn threads using ExecutorService (as mentioned by FauxFaux). This will allow you to easily pass information about the error to main thread. Besides that, using ExecutorService allows you to write less code. You won't have to manage threads in your code but leave it for ExecutorService instead.
beacuse , recently, I have write a program with about 3 threads in order to fill a lot data from mysql and mongoDb to ElasticSearch. I share u my code.
I use java.util.concurrent.Executors.
First I have a main class. It calls
public void start() throws Exception {
this.logger.info("Main: Start the worker manually");
schedulerThreadPool = Executors.newScheduledThreadPool(this.maxNumberOfThread);
for (int i = 0; i < this.maxNumberOfThread; i++) {
Worker worker = new Worker();
long delay = i * this.sleepBetweenTaskStart;
schedulerThreadPool.scheduleAtFixedRate(worker, delay, this.minTimeBetweenEachTask, TimeUnit.MILLISECONDS);
}
}
And Worker implements Runnable and get Thread Id by below code.
this.threadId = Thread.currentThread().getId();
And just try catch in each Worker. Everything works normally.
#Override
public void run() {
try {
do...
} catch (Exception e) {
e.printStackTrace();
}
}
I have a project for my "Operating Systems". I need to write 2 programs with java...
write a program that produce Water with 2 method Oxygen and Hydrogen.
method Oxygen produce one Oxygen and method Hydrogen produce one hydrogen. when 2 Hydrogen and one Oxygen was existed H2O created. I must write this with with Semaphores and threads.
Write the above problem with Monitors and Sychronize.
I've writed some code for this but it gives illegal monitor exeption...
please help me to correct it...
This is my code:
// class for implement Thread for oxygen
public class Thread_O implements Runnable {
public void run() {
thread t = new thread();
try {
t.oxygen();
} catch (InterruptedException ex) {
Logger logger = Logger.getLogger(Thread_O.class.getName());
logger.log(Level.SEVERE, null, ex);
}
}
}
// class for implement Thread for Hydrogen
public class Thread_H implements Runnable {
public void run() {
thread t = new thread();
try {
t.Hydrogen();
} catch (InterruptedException ex) {
Logger logger = Logger.getLogger(Thread_H.class.getName());
logger.log(Level.SEVERE, null, ex);
}
}
}
//class for method Oxygen and Hydrogen
public class thread {
Semaphore O = new Semaphore(0, true);
Semaphore H = new Semaphore(0, true);
Semaphore H2O = new Semaphore(0, true);
Semaphore safe = new Semaphore(1, true);
public void oxygen() throws InterruptedException {
safe.wait();
H.wait();
H.wait();
H2O.release();
H2O.release();
Safe.release();
// System.out.println("O2...!");
}
public void Hydrogen() throws InterruptedException {
H.release();
H2O.wait();
// System.out.println("H2...!");
}
}
and in action of Oxygen Button:
Thread th = new Thread(new Thread_O());
th.start();
I'm not going to decode your homework for you, but an IllegalMonitorException is thrown when you're trying to wait() on an object without being synchronized. So to wait for an object called list:
synchronized (list) {
try {
list.wait();
} catch(Throwable t) {
t.printStackTrace();
}
}
You have to understand how the producer/consumer mechanism work.
Here you'll have one consumer thread and two producers.
First you'll have one thread producing oxygen, and other producing hydrogen.
Then, those molecules should be places "somewhere" ok? That "something" is the thing that has to be monitored and synchronized.
So it should go something like this:
class Water {
char [] waterMolecule = new char[3]; // <-- synchronize access to this
char hydrogen(){
return 'H';
}
char oxygen() {
return 'O';
}
void produce() {
Thread t = new Thread( new Runnable() {
synchronize( waterMolecule ) {
waterMolecule[0] = hydrogen();
}
}):
.... produce the others
}
void consume() {
synchronize watermolecule
if waterMolecule is complete
create water and clean out the molecule.
}
}
That's the basic idea.
Just bear in mind that you won't be able to produce another particle of oxigen until the previous one has been consumed.
Also you must always call wait in a while loop
Here's how that wait/synchronize should be coded.
Here's a number of producer/consumer samples.
Although your homework is already due, I'd like to propose CyclicBarrier as the best solution for this scenario.
It allows some kind of rendezvous for the different threads (here: your molecule producers) and triggers the execution of an additional runnable on completition (here: creation of h20).