How can i use callback method on my java code? - java

public class DowloadEngine implements Runnable {
public DowloadEngine(CallBack c) {
callback = c;
}
public interface CallBack {
public void processDone(String message);
}
private final CallBack callback;
#Override
public void run() {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {}
callback.processDone("'CallBack' func is called");
}
}
And there is my main class in here
public class GUI implements DowloadEngine.CallBack{
public static void main(String[] args){
Thread thread = new Thread(new DowloadEngine(this));// Error :Make main not static!!
thread.start();
//wait a little to see the result
Scanner scan = new Scanner(System.in);
scan.nextLine();
//wait a little to see the result
}
#Override
public void processDone(String message) {
//code ...
//code ...
//code ...
System.out.println(message);
}
}
I want to do all works on main class via callback method but I did not understand these methodology. How does it works?
How can i use these with together?

Change:
Thread thread = new Thread(new DowloadEngine(this)); to
Thread thread = new Thread(new DowloadEngine(new GUI()));

Related

Why doesn't the volatile keyword work as expected in java code?

I'm learning concurrency knowledge in Java. About volatile keyword, it should make variable visible in different threads. But in my demo code, it doesn't seem to work as expected. The method run() in the class which implements Runnable will never stop.
public class VisibilityDemo {
public static void main(String[] args) throws InterruptedException {
TimeConsumingTask timeConsumingTask = new TimeConsumingTask();
Thread thread = new Thread(new TimeConsumingTask());
thread.start();
Thread.sleep(3000);
timeConsumingTask.cancel();
}
}
class TimeConsumingTask implements Runnable {
private volatile boolean toCancel = false;
#Override
public void run() {
while (! toCancel) {
System.out.println("executing...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (toCancel) {
System.out.println("Task was canceled.");
} else {
System.out.println("Task done.");
}
}
public void cancel() {
toCancel = true;
System.out.println(this + " canceled.");
}
}
In your main method you have two instances of your task:
public static void main(String[] args) throws InterruptedException {
TimeConsumingTask timeConsumingTask = new TimeConsumingTask(); //<-- one
Thread thread = new Thread(new TimeConsumingTask()); //<-- two
thread.start();
Thread.sleep(3000);
timeConsumingTask.cancel(); //<-- cancel() on first
}
}
You're passing one to the Thread constructor and then call cancel on the other one. You need to call cancel on the instance passed to Thread, like so:
public static void main(String[] args) throws InterruptedException {
TimeConsumingTask timeConsumingTask = new TimeConsumingTask();
Thread thread = new Thread(timeConsumingTask); //<-- difference here
thread.start();
Thread.sleep(3000);
timeConsumingTask.cancel();
}
}

Executor Service: SingleThreadExecutor not firing runnable object

I am trying to execute a runnable object using the Java concurrency package's, ExecutorService SingleThreadExecutor. When I call the execute a command on the new Runnable object it simply steps over it. i.e. the run() method isn't called.
I have stepped through my lines of code using the debugger and can see my SingleThreadExecutor has been created and my Runnable is initialised.
public class RunnableDemo {
public ExecutorService executor;
public RunnableDemo () {
this.executor = Executors.newSingleThreadExecutor();
}
public void start(){
executor.execute(new MyRunnable("Hello World"));
}
public static void main(String[] args){
RunnableDemo app = new RunnableDemo();
app.start();
}
}
public class MyRunnable implements Runnable {
private String strToPrint;
public MyRunnable(String parameter) {
this.strToPrint = parameter;
}
public void run() {
System.out.println(strToPrint);
}
}
And probably self-explanatory but in this scenario, I would expect to see "Hello World" printed to screen. However, the execute/run method doesn't seem to be invoked after the runnable is created.
Your program is terminating before the executer starts the task.
You have to wait for the executor to finish like this:
public class RunnableDemo {
public ExecutorService executor;
public RunnableDemo () {
this.executor = Executors.newSingleThreadExecutor();
}
public void start(){
executor.execute(new MyRunnable("Hello World"));
}
public void awaitTermination(){
try {
service.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args){
RunnableDemo app = new RunnableDemo();
app.start();
app.awaitTermination();
}
}
public class MyRunnable implements Runnable {
private String strToPrint;
public MyRunnable(String parameter) {
this.strToPrint = parameter;
}
public void run() {
System.out.println(strToPrint);
}
}

How do I implement thread wait notify in this case?

I have 2 classes. One method of the class calls the other class' method, but it has to wait until the method finishes to proceed to the execution of the rest of the code.
This is a rough code of what I'm trying to make. And I know this doesn't work.
public class Example
{
Thread thread;
public Example(Thread thread)
{
this.thread = thread;
}
public void doSomethingElse()
{
System.out.println("Do something else");
thread.notify();
}
}
public class Example2
{
Thread thread;
Example example;
public Example2()
{
example = new Example(thread);
thread = new Thread()
{
public void run()
{
example.doSomethingElse();
try {
this.wait();
} catch (InterruptedException ex) {
}
System.out.println("Do something");
}
};
}
public void doSomething()
{
thread.run();
}
}
Now do you know how to make this right?
Not sure if your constrained to using this particular approach (wait/notify) however a better approach is taking advantage of the Java Concurrency API
public class ExampleCountDownLatch
{
public void doSomething () throws InterruptedException
{
final CountDownLatch latch = new CountDownLatch(1);
Thread thread = new Thread()
{
public void run ()
{
System.out.println("do something");
latch.countDown();
}
};
System.out.println("waiting for execution of method in your example class");
thread.start();
// wait for reasonable time otherwise kill off the process cause it took
// too long.
latch.await(3000, TimeUnit.MILLISECONDS);
// now I can do something from your example 2
System.out.println("now i can execute from example 2 do something else");
}
}
Anyway just another approach if you had an option.
UPDATE:
Here is a blog about this very topic.
Couple of points :
you should acquire lock before calling wait or notify method. The
lock must be on same object. In code you are calling wait on example2
object but calling notify on different object.
thread.run() means calling run method of thread object, its not
creating new thread its same as example.doSomething(). When you
create thread start that thread by calling start method.
Here is my implementation
class Example implements Runnable
{
public void run()
{
doSomething();
}
public void doSomething(){
synchronized(this){
System.out.println("Do something else");
try{
Thread.sleep(1000);
this.notify();
}catch (InterruptedException ignore) {}
}
}
}
class Example2 implements Runnable
{
Thread thread;
Example example;
public Example2(Example example){
this.example = example;
}
public void run(){
doSomething();
}
public void doSomething(){
synchronized(example){
System.out.println("waiting for example 1 to complete");
try{
example.wait();
}catch (InterruptedException ignore) {}
}
System.out.println("Do something");
}
}
public class Entry{
public static void main(String[] args){
Example example = new Example();
Example2 obj = new Example2(example);
Thread t = new Thread(obj);
t.start();
Thread t2 = new Thread(example);
t2.start();
}
}
In code Thread.sleep(1000); statement is not needed.
Here is one more implementation using join method
class Example implements Runnable
{
public void run()
{
doSomething();
}
public void doSomething(){
System.out.println("Do something else");
try{
Thread.sleep(1000);
}catch (InterruptedException ignore) {}
}
}
class Example2 implements Runnable
{
Thread thread;
Example example;
public Example2(Example example){
this.example = example;
}
public void run(){
System.out.println("waiting for example 1 to complete");
Thread t = new Thread(example);
try{
t.start();
t.join();
}catch(InterruptedException ie){
}
doSomething();
}
public void doSomething(){
System.out.println("Do something");
}
}
public class Entry{
public static void main(String[] args){
Example example = new Example();
Example2 obj = new Example2(example);
Thread t = new Thread(obj);
t.start();
}
}

Thread Dependency Java

I have a main class which spawns a thread, let's call them MainClass and MyThread.
public class MainClass extends javax.swing.JFrame {
int sharedVariable;
MyThread threadInstance;
public MainClass (){
sharedVariable = 2;
threadInstance = new MyThread(this);
threadInstance.run();
}
public int getSharedVariable(){ return sharedVariable; }
public static void main(String[] args){
//begin main class
}
}
public class MyThread implements Runnable {
MainClass class;
public MyThread(MainClass main_class){
this.main_class= main_class;
}
#Override
public run(){
while(this.main_class is still active){
//grab status of sharedVariable and wait for x amount of time.
}
}
}
The problem is I do not know how to implement the while condition which checks if the MainClass instance is still alive and if it is, it has to use the this.main_class.getSharedVariable() to get the value of sharedVariable, then wait for x amount of time. MainClass has the main method .
I would recommend holding onto the Thread instance and then calling threadInstance.interrupt() right before the main(...) method exits.
Something like:
public static void main(String[] args){
MainClass mainClass = new MainClass();
try {
...
// do main stuff here
...
} finally {
mainClass.threadInstance.interrupt();
}
}
Then in your thread you'd do:
while(!Thread.currentThread().isInterrupted()){
...
}
You'd also want to handle InterruptedException correctly:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// always a good pattern to re-interrupt the thread here
Thread.currentThread().interrupt();
// if we are interrupted quit
return;
}
Btw, it is very bad form to leak the instance of an object during construction to another thread:
new MyThread(this);
See here: Why shouldn't I use Thread.start() in the constructor of my class?
Also, you aren't starting a thread when you call threadInstance.run();. You are just running it in the current thread. You should use threadInstance.start() but not inside of the constructor like that.
You can use CountDownLatch which is very convenient for such tasks as waiting other threads to finish some activity (you can change Thread.sleep(...) argument in main to, say, 12000L and see what happens):
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
class OtherThread extends Thread {
private final CountDownLatch sharedLatch;
OtherThread(CountDownLatch sharedLatch) {
this.sharedLatch = sharedLatch;
}
#Override
public void run() {
boolean wokenByMain = false;
try {
wokenByMain = sharedLatch.await(10000L, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
return; // or not return, whatever makes more sense in your case
}
System.out.println("heh: " + wokenByMain);
}
}
class SOSample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(1);
OtherThread otherThread = new OtherThread(latch);
otherThread.start();
System.out.println("Scheduled other thread to be started");
Thread.sleep(1000L);
System.out.println("going to release other thread");
latch.countDown();
}
}
public class MainClass extends JFrame implements Runnable {
public static void main(String [] args) {
final Thread t=new Thread(new MainClass() {
public void run(){
//something
});
Thread t2=new Thread(new MyThread() {
public void run() {
while(t.isAlive) {
//something
}
}
});
}
}

Creating Multiple Threaded Loops

Sorry if this a bit of a basic question but I've been thinking about doing multiple sprite loops and for the first time I tried to create two threads in main, both with while(true) loops. My intention: to have two threads looping simultaneously. However when I run the program it seems to interrupt the flow of execution and the second loop doesn't getting executed in a new thread but just stops with the program stuck on the first endless while() loop of a thread. I think it is still just executing the main thread rather than starting a new one and then continuing on.
I've tried it two ways:
Once with Threads:
public class Zzz {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
r1 r = new r1();
r2 a = new r2();
r.start();
a.start();
}
}
public class r1 extends Thread {
#Override
public void start() {
while(true) {
System.out.println("r1");
try {
this.sleep(100);
} catch (Exception ex) {
}
}
}
}
public class r2 extends Thread {
#Override
public void start() {
while(true) {
System.out.println("r2");
try {
this.sleep(100);
} catch (Exception ex) {
}
}
}
}
And once with Runnable:
public class Zzz {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
r1 r = new r1();
r2 a = new r2();
r.run();
a.run();
}
}
public class r1 implements Runnable {
#Override
public void run() {
while(true) {
System.out.println("r1");
try {
Thread.sleep(100);
} catch (Exception ex) {
}
}
}
}
public class r2 implements Runnable {
#Override
public void run() {
while(true) {
System.out.println("r2");
try {
Thread.sleep(100);
} catch (Exception ex) {
}
}
}
}
But to no avail. It always gets stuck at R1. Any ideas anyone? I've googled and looked around about threads and I can't find this covered anywhere.
You need to override run method & in case of runnable you need to create instance of Thread
public class MyThread extends Thread{
#Override
public void run() {
while(true) {
System.out.println("My Thread running");
}
}
ánd for the case of Runnable
class MyRunnable implements Runnable{
public void run(){
System.out.println("I am executing by Thread: " + Thread.currentThread().getName());
}
}
and
Thread mythread = new MyThread();
mythread.setName("T1");
Thread myrunnable = new Thread(new MyRunnable());
myrunnable.start();
To start threads, you need to create two Threads from the Runnables and start them:
Thread t1 = new Thread(r);
Thread t2 = new Thread(a);
t1.start();
t2.start();
Define classes r1 and r2 as :
public class Thread1 extends Thread {
#Override
public void run() {
System.out.println("r1");
try {
this.sleep(100);
} catch (Exception ex) {
}
}
}
public class Thread2 extends Thread {
#Override
public void run() {
System.out.println("r2");
try {
this.sleep(100);
} catch (Exception ex) {
}
}
}
public class ThreadTester {
public static void main(String[] args) {
Thread1 r = new Thread1();
Thread2 a = new Thread2();
r.start();
a.start();
}
}
Using Runnable :
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
check java documentation for more info

Categories