Java and 2 threads - java

I am trying to learn Java's threads in order to do an assignment, but I do not understand how I can make each thread to do its own code. I also get an error:
Program.java:1: error: Program is not abstract and does not override abstract me
thod run() in Runnable
public class Program implements Runnable {
^
1 error
Because it is required by the assignment, I have to do everything within the same file, so I tried the code below:
public class Program implements Runnable {
Thread thread1 = new Thread () {
public void run () {
System.out.println("test1");
}
};
Thread thread2 = new Thread () {
public void run () {
System.out.println("test2");
}
};
public void main (String[] args) {
thread1.start();
thread2.start();
}
}
Could you please fix it for me and show how to have 2 threads which do different tasks from each other? I have already seen examples that print threads' names, but I did not find them helpful.
Thank you.

Your Program class is defined as implementing the Runnable interface. It therefore must override and implement the run() method:
public void run () {
}
Since your two Thread objects are using anonymous inner Runnable classes, you do not need and your should remove the implements Runnable from your Program class definition.
public class Program {
...

try this:
class Program {
public static void main(String[] args) {
Thread thread1 = new Thread() {
#Override
public void run() {
System.out.println("test1");
}
};
Thread thread2 = new Thread() {
#Override
public void run() {
System.out.println("test2");
}
};
thread1.start();
thread2.start();
}
Or you can create a separate class implementing Runnable and ovverriding method run().
Then in main method create an instance of Thread with you class object as argument :
class SomeClass implements Runnable {
#Override
run(){
...
}
}
and in main:
Thread thread = new Thread(new SomeClass());

When you implement an interface (such as Runnable) you must implement its methods, in this case run.
Otherwise for your app to compile and run just erase the implements Runnable from your class declaration:
public class Program {
public void main (String[] args) {
Thread thread1 = new Thread () {
public void run () {
System.out.println("test1");
}
};
Thread thread2 = new Thread () {
public void run () {
System.out.println("test2");
}
};
thread1.start();
thread2.start();
}
}

Related

How i can create new thread to do some task and stop the thread after the task finish

its seems to be a stupid question but I'm trying to create a task in a new thread, and after the task is finished the thread should exit without calling anything to stop it from main.
Here is an example:
public class Main {
public static void main(String[] args) {
// write your code here
foo f1= new foo();
Thread t= new Thread(f1);
f1.doSomething();
}
}
class foo extends Thread{
void doSomething(){
// download File for example
}
}
if I implement the run method like this :
class foo extends Thread{
void doSomething(){
// download File for example
}
void run(){
doSomething();
}
}
it is going to call doSomething() method forever.
foo f1= new foo();
Thread t= new Thread(f1);
f1.doSomething();
This is not the away to start a thread. Basically you call thread.start() method to start the thread which will execute everything which is there in run method.
Please go through the tutorial first
https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
Here is one solution:
public class ThreadExample extends Thread {
private void doSomething(){
System.out.println("Inside : doSomething()");
}
#Override
public void run() {
System.out.println("Inside : " + Thread.currentThread().getName());
doSomething();
}
public static void main(String[] args) {
System.out.println("Inside : " + Thread.currentThread().getName());
System.out.println("Creating thread...");
Thread thread = new ThreadExample ();
System.out.println("Starting thread...");
thread.start();
}
}
One output:
Inside : main
Creating thread...
Starting thread...
Inside : Thread-0
Inside : doSomething()
For further informations, check out this Java Concurrency and Multithreading tutorial.

Unexpected output. Please explain

I've been trying to figure out the reasons behind the output of the following Java program:
public class Main {
public static void main(String args[]) {
Runnable r = new Runnable() {
#Override
public void run() {
System.out.println("Implementation");
}
};
MyThread gaurav = new MyThread(r);
new Thread(r).start();
gaurav.start();
}
}
class MyThread extends Thread {
Runnable runnable;
public MyThread(Runnable r) {
runnable = r;
}
#Override
public void run() {
super.run();
System.out.println("Thread");
}
}
Output for above is : 'Implementation' followed by 'Thread' in next line. Now the problem lies in this statement :
gaurav.start();
As I have passed the runnable r to MyThread, I thought that r would get executed, hence, the output would be 'Implementation' for this too. But clearly, I am missing something. Also a difference between the statements:
new Thread(r).start();
gaurav.start();
for this scenario would be really useful. Thanks.
Consider the following:
public class Main {
public static void main(String args[]) {
Runnable r = new Runnable() {
#Override
public void run() {
System.out.println("Implementation");
}
};
MyThread gaurav = new MyThread(r);
gaurav.start();
}
}
class MyThread extends Thread {
Runnable runnable;
public MyThread(Runnable r) {
// calling Thread(Runnable r) constructor.
super(r);
// runnable isn't used anywhere. You can omit the following line.
runnable = r;
}
#Override
public void run() {
// First it will run whatever Runnable is given
// into Thread's constructor.
super.run();
System.out.println("Thread");
}
}
Output:
Implementation
Thread
I guess your confusion comes from your Runnable field in MyThread. You think that by having it there, you somehow override Thread's own runnable but you don't. If you want to do that, you should call super(r) in your constructor.
MyThread's start method will start the thread's run method in which you have System.out.println("Thread");
While new Thread(r).start(); will run the System.out.println("Implementation");
It's solely on OS's scheduler which thread would run first. So you might see the output as:
Implementation
Thread
Or
Thread
Implementation

Why doesn't run method call?

I've write the following example:
public class MyThread extends Thread{
MyThread(Runnable r){
super(r);
}
public void run(){
System.out.println("run");
}
}
public static void main(String[] args)
{
Thread t = new MyThread(new Runnable() {
#Override
public void run() {
System.out.println("rrrrrrrrrruuuuuuuuuuuun");
}
});
t.start(); //run
}
Why does run methdo defined in MyThread was called instead?
Because the default behavior of a thread constructed with a Runnable is to delegate to the runnable passed as argument to the constructor. But you overrode run() in the thread itself, so instead of delegating to the runnable, it executes the code inside the overridden run() method.
For the record, here's the default implementation of Thread.run(), that you overrode:
private Runnable target;
public void run() {
if (target != null) {
target.run();
}
}
Because you the MyThread.run is not override, but the Runnable.run is. Now if you look at your implementation of MyThread.run, the stored Runnable plays no part in it. In other words, it doesn't matter what kind of runnable you give with the constructor. You should use:
public static void main(String[] args)
{
Thread t = new MyThread() {
#Override
public void run() {
System.out.println("rrrrrrrrrruuuuuuuuuuuun");
}
});
t.start(); //run
}
As #BorisTheSpider notes, overriding a Thread is in general not good practice: a Thread has the responsibility to start a Thread and give control to a runnable. A better implementation would be:
public static void main(String[] args)
{
Thread t = new Thread(new MyThread() {
#Override
public void run() {
System.out.println("rrrrrrrrrruuuuuuuuuuuun");
}
}));
t.start(); //run
}

Thread safe class is being terminated

I have a thread safe class like the following
public class ThreadedClass extends Thread {
public ThreadedClass() {
// Some code
listener();
}
public void run() {
// Some code
}
public void listener() {
// Code that's checking for messages from a server
String test = // lots of stuff here
}
}
This is being executed in a test class like the following
public class Test {
public static void main(String[] args) {
ThreadedClass t1 = new t1();
t1.start();
}
}
The problem is, I want to have a callback from the thread that's running, so when listener() get's a message I can notify Test(), check the message, and perform some action. To do this I wrote an interface and added the following to listener()
this.callback.messageRecieved(message);
This executes, but terminates the thread. Thoughts? Thanks!
public class Test {
public void notify(){//notify};
public static void main(String[] args) {
//Main Thread here 1
ThreadedClass t1 = ThreadedClass.getInstance();
//Main Thread 3
//Main Thread starts a Thread : Thread-1
t1.start();
//*****Main Thread 4 (Parallel Execution here. Thread-1 is listening when Main Thread is here)
}
}
public class ThreadedClass extends Thread {
private ThreadedClass instance = null;
private ThreadedClass() {
}
public static synchronized ThreadedClass getInstance(){
//Main Thread 2
if(instance == null){
return instance = new ThreadedClass();
}
return this.instance;
}
public void run() {
//Thread-1 1
listener();
//Thread-1 2
}
public void listener() {
// Code that's checking for messages from a server
String text = // lots of stuff here
}
}
As I understand your code,you are writing socket programming.You call listener method in constructor
and listener has input stream with blocks ThreadedClass initialization.
I write the listener method call in run method so when you start the thread listener method will be called. Also I pass the Test refrence in ThreadedClass so you can call any method in Test
Also your classes are always thread safe. You are not using static method or singleton class.
If you initialize for each class you don't have any problem with multi threading issues.

How to run a class' method using thread

If I do the following, I will be able to create an object as a thread and run it.
class ThreadTest
{
public static voic main(String[] args)
{
HelloThread hello = new HelloThread();
Thread t = new Thread(hello);
t.start();
}
}
class HelloThread extends Thread
{
public void run()
{
System.out.println(" Hello ");
}
}
Now, if my HelloThread class has a another method call runThisPlease(), how are we supposed to run it with a thread?
Example:
class HelloThread extends Thread
{
public void run()
{
System.out.println(" Hello ");
}
public void runThisPlease(String input)
{
System.out.println (" Using thread on another class method: " + input );
}
}
Que: When I try Thread t = new Thread(hello.runThisPlease());, it doesn't work. So how can we call the method runThisPlease() using a thread?
Edit: Argument needed in method for runThisPlease();
In java 8 you can use
Thread t = new Thread(hello::runThisPlease);
hello::runThisPlease will be converted to a Runnable with a run method that calls hello.runThisPlease();.
If your want to call a method, that needs parameters, e.g. System.out.println, you can of course use a normal lambda expression too:
final String parameter = "hello world";
Thread t = new Thread(() -> System.out.println(parameter));
If you use a java version < 8, you can of course replace the method reference / lambda expression with anonymus inner classes that extend Runnable (which is what a java8 compiler does, AFAIK), see other answers.
However you can also use a anonymus inner class that extends Thread:
final HelloThread hello = //...
Thread t = new Thread() {
#Override
public void run() {
hello.runThisPlease();
}
};
Simply calling the runThisPlease() from within the run() method will make it part of a new thread.
Try this:
class HelloThread extends Thread
{
public void run()
{
System.out.println(" Hello .. Invoking runThisPlease()");
runThisPlease();
}
public void runThisPlease()
{
System.out.println (" Using thread on another class method ");
}
}
Things are maybe more clear if you use the Runnable interface:
public class HelloThread implements Runnable
{
#Override
public void run() {
// executed when the thread is started
runThisPlease();
}
public void runThisPlease() {...}
}
To launch this call:
Thread t=new Thread(new HelloThread());
t.start();
The Thread class can not see your extra method because it is not part of the Runnable interface.
As a convenience Thread implements Runnable but I don't think it helps in clarity :(
You have to only call this method inside run() method.
public void run(){
System.out.println(" Hello ");
runThisPlease();
}
If you want to pass some argument then you can use below code
String str = "Welcome";
Thread t = new Thread(new Runnable() {
public void run() {
System.out.println(str);
}});

Categories