Thread safe class is being terminated - java

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.

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.

java thread not running even after start call

public class TestSynchronization {
public static void main(String[] args) {
ThreadTest[] threads = new ThreadTest[10];
int i = 0;
for(Thread th : threads) {
th = new Thread(Integer.toString(i++));
th.start();
}
}
class ThreadTest extends Thread {
TestSynchronization ts = new TestSynchronization();
public /*synchronized */void run() {
synchronized(this) {
ts.testingOneThreadEntry(this);
System.out.println(new Date());
System.out.println("Hey! I just came out and it was fun... ");
this.notify();
}
}
}
private synchronized void testingOneThreadEntry(Thread threadInside) {
System.out.println(threadInside.getName() + " is in");
System.out.println("Hey! I am inside and I am enjoying");
try {
threadInside.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I am not able to start the ThreadTest instances.
I expect that ThreadTest's run method be executed as soon as the line th.start(); is executed, the one inside main method.
When I run the program, I see niether my system.out nor any exception.
I debugged also, but could see loop runs 10 times.
You just started a Thread, not a ThreadTest. Thread's run() method does nothing. Instead, create and start() a ThreadTest.
for(ThreadTest th : threads) {
th = new ThreadTest(Integer.toString(i++));
th.start();
}
You'll also need a one-arg constructor in your ThreadTest class that will take the String you're passing to it.
public ThreadTest(String msg){
super(msg);
}
You'll also need to make the ThreadTest class static so you can access that nested class from the static main method.
static class ThreadTest extends Thread {
However, you'll wind up will all Threads waiting. As written, this code will call wait inside every Thread, but it will never get to notify. The notify method must be called on the Thread to be notified, from another Thread. If it's waiting, then it can never notify itself.
You have array of ThreadTest (thread) class which is not used.
I assume you wanted this:
public static void main(String[] args) {
ThreadTest[] threads = new ThreadTest[10];
int i = 0;
for(int i=0;i<threads.length;i++) {
threads[i] = new ThreadTest();
threads[i].start();
}
}

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);
}});

How to access a method from another running thread in java

I am new to Java Threads. What I am trying to do is from ThreadB object gain access to the instance of a current running thread, ThreadA, and call its method called setSomething.
1) I think I am making harder than it really is
2) I have a null pointer exception so I must be doing something wrong when accessing that method
Here is what I have so far and I have done my due diligence and looked here on StackOverflow for a similar question.
I have a current Thread running in the background:
// assume this thread is called by some other application
public class ThreadA implements Runnable{
private Thread aThread;
public ThreadA(){
aThread = new Thread(this);
aThread.setName("AThread");
aThread.start();
}
#Override
public void run(){
while(true){
// doing something
}
}
public void setSomething(String status){
// process something
}
}
// assume this thread is started by another application
public class ThreadB implements Runnable{
#Override
public void run(){
passAValue("New");
}
public void passAValue(String status){
// What I am trying to do is to get the instance of ThreadA and call
// its method setSomething but I am probably making it harder on myself
// not fully understanding threads
Method[] methods = null;
// get all current running threads and find the thread i want
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for(Thread t : threadSet){
if(t.getName().equals("AThread")){
methods = t.getClass().getMethods();
}
}
//**How do I access ThreadA's method, setSomething**
}
}
Thank you in advance
Allen
Wow why do you make things to much complex?! this is not as hard as you think (killing a dragon in a dark castle!)
okay all you need to do is passing the threadA references to threadB! just this. and let me say that when you call a method from thread b, so it runs by thread b, not the class has been hosted.
class ThreadA implements Runnable {
public void run() {
//do something
}
public void setSomething() { }
}
class ThreadB implements Runnable {
private ThreadA aref;
public ThreadB(ThreadA ref) { aref = ref; }
public void run() {
aref.setSomething(); // Calling setSomething() with this thread! (not thread a)
}
}
class Foo {
public static void main(String...arg) {
ThreadA a = new ThreadA();
new Thread(a).start();
ThreadB b = new ThreadB(a);
new Thread(b).start();
}
}
and here a simple threadtutorial
When or after you instantiate your ThreadB object, give it a reference to your ThreadA object instance. Something like:
ThreadA a = new ThreadA();
ThreadB b = new ThreadB(a);
Then, within the ThreadB code, you can just invoke ThreadA's method by using the reference you have no doubt stored in an instance variable in ThreadB.

Java and 2 threads

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();
}
}

Categories