Understanding Runnable in Android - java

I was going through Handlers, the post method in it accepts a parameter of type Runnable. There's a following code snippet I came across
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
timeView.clearComposingText();
Integer hours = seconds/3600;
Integer minutes = (seconds % 3600)/60;
Integer secs = seconds % 60;
String time = String.format("%d:%02d:%02d",hours,minutes,secs);
timeView.setText(time);
if(running)
{
seconds++;
}
handler.postDelayed(this,1000);
}
});
Now since Runnable is an Interface in Java, how are we able to create a new instance of Runnable directly?

Anonymous classes can implement interfaces, and that's the only time you'll see a class implementing an interface without the "implements" keyword.
A complete example might look like:
public class MyClass {
public interface A {
void foo();
}
public interface B {
void bar();
}
public interface C extends A, B {
void baz();
}
public void doIt(C c) {
c.foo();
c.bar();
c.baz();
}
public static void main(String[] args) {
MyClass mc = new MyClass();
mc.doIt(new C() {
#Override
public void foo() {
System.out.println("foo()");
}
#Override
public void bar() {
System.out.println("bar()");
}
#Override
public void baz() {
System.out.println("baz()");
}
});
}
}
The output of this example is:
foo()
bar()
baz()

Related

Multiple threads in on class

I'm trying to create two classes that extends from Thread, I know how to create one class.
public class Main {
class Thred1 extends Thread {
public void run() {
System.out.println("I'm watching a video...");
}
}
class Thred2 extends Thread {
public void run() {
System.out.println("I'm eating...");
}
}
public static void main (String[] args) {
Thred1 t11 = new Thred1();
Thred2 t12 = new Thred2();
t11.start();
t12.start();
}
}
And got Main.java:15: error: non-static variable this cannot be referenced from a static context
Is there better way to implement my idea?
Your problem is with inner classes and not with threads , try to put all this code in the same file Main.java :
class Thred1 extends Thread {
public void run() {
System.out.println("I'm watching a video...");
}
}
class Thred2 extends Thread {
public void run() {
System.out.println("I'm eating...");
}
}
public class Main {
public static void main (String[] args) {
Thred1 t11 = new Thred1();
Thred2 t12 = new Thred2();
t11.start();
t12.start();
}
}
Another possible solution is to use static classes instead of the member inner classes used in your code :
public class Main {
static class Thred1 extends Thread {
public void run() {
System.out.println("I'm watching a video...");
}
}
static class Thred2 extends Thread {
public void run() {
System.out.println("I'm eating...");
}
}
public static void main(String[] args) {
Thred1 t11 = new Thred1();
Thred2 t12 = new Thred2();
t11.start();
t12.start();
}
}
Or simply you can use Lambda expression , Thread class have a constructor who accept a Runnable as parameter , Runnable is a functional interface so you can pass a Lambda expression as argument like that :
public class Main {
public static void main(String[] args) {
Thread t11 = new Thread(()->System.out.println("I'm watching a video..."));
Thread t12 = new Thread(()->System.out.println("I'm eating..."));
t11.start();
t12.start();
}
}

How can i use callback method on my java code?

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

C++: Pass interface as parameter like in Java

I want to do some stuff in C++ that i can do in Java. Here is my Java code:
interface Worker
{
public void work();
}
class Employer
{
public void askForWork(Worker worker)
{
worker.work();
}
}
public class Main
{
public static void main(String[] args)
{
Employer employer = new Employer();
employer.askForWork(new Worker()
{
#Override
public void work()
{
System.out.println("I'm working!");
}
});
employer.askForWork(new Worker()
{
#Override
public void work()
{
System.out.println("I'm working too!");
}
});
}
}
And I want to do it in C++. It is very important for me to be able to implement interface inside function call. Is it possible?
One way to do it is use std::function.
class Worker {
public:
explicit Worker(std::function<void()> task)
: task_(task) {}
void Work() {
task_();
}
private:
std::function<void()> task_;
};
class Employer {
...
void AskForWork(std::unique_ptr<Worker> worker) {
worker->Work();
}
};
int main(...) {
Employer employer;
employer.AskForWork(new Worker(
[]() {
std::cout << "I'm working!" << std::endl;
}
));
}

How to run two classes in parallel using multithreading?

I am working on a project in which I have multiple interface and two Implementations classes which needs to implement these two interfaces.
Suppose my first Interface is -
public Interface interfaceA {
public String abc() throws Exception;
}
And its implementation is -
public class TestA implements interfaceA {
// abc method
}
I am calling it like this -
TestA testA = new TestA();
testA.abc();
Now my second interface is -
public Interface interfaceB {
public String xyz() throws Exception;
}
And its implementation is -
public class TestB implements interfaceB {
// xyz method
}
I am calling it like this -
TestB testB = new TestB();
testB.xyz();
Problem Statement:-
Now my question is - Is there any way, I can execute these two implementation classes in parallel? I don't want to run it in sequential.
Meaning, I want to run TestA and TestB implementation in parallel? Is this possible to do?
Sure it is possible. You have actually many options. Preferred one is using callable and executors.
final ExecutorService executorService = Executors.newFixedThreadPool(2);
final ArrayList<Callable<String>> tasks = Lists.newArrayList(
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testA.abc();
}
},
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testB.xyz();
}
}
);
executorService.invokeAll(tasks);
This method gives you opportunity to get a result from executions of your tasks. InvokeAll returns a list of Future objects.
final List<Future<String>> futures = executorService.invokeAll(tasks);
for (Future<String> future : futures)
{
final String resultOfTask = future.get();
System.out.println(resultOfTask);
}
You can make your code easier to use if you make your classes implements Callable, then you will reduce amount of code needed to prepare list of tasks. Let's use TestB class as an example:
public interface interfaceB {
String xyz() throws Exception;
}
public class TestB implements interfaceB, Callable<String>{
#Override
public String xyz() throws Exception
{
//do something
return "xyz";
}
#Override
public String call() throws Exception
{
return xyz();
}
}
Then you will need just
Lists.newArrayList(new TestB(), new TestA());
instead of
final ArrayList<Callable<String>> tasks = Lists.newArrayList(
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testA.abc();
}
},
new Callable<String>()
{
#Override
public String call() throws Exception
{
return testB.xyz();
}
}
);
Whats more, executors gives you power to maintain and reuse Thread objects which is good from performance and maintainability perspective.
Create Two Thread and run two implementation parallely. Code snippet -
ThreadA{
public void run(){
TestA testA = new TestA();
testA.abc();
}
}
...
ThreadB{
public void run(){
TestB testB = new TestB();
testB.xyz();
}
}
Start this two thread from main method -
public static void main(String[] args){
new ThreadA().start();
new ThreadB().start();
}
Try this one
Collect all the classes of same interface and call them in Multi threading.
Use Callback mechanism to get the result back
import java.util.ArrayList;
import java.util.List;
public class Demo123 {
public static void main(String[] args) {
List<InterfaceA> a = new ArrayList<InterfaceA>();
List<InterfaceB> b = new ArrayList<InterfaceB>();
TestA testA = new TestA();
TestB testB = new TestB();
a.add(testA);
b.add(testB);
for (final InterfaceA i : a) {
new Thread(new Runnable() {
#Override
public void run() {
try {
i.callback(i.abc());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
for (final InterfaceB i : b) {
new Thread(new Runnable() {
#Override
public void run() {
try {
i.callback(i.xyz());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
}
interface MyCallback {
public void callback(String value);
}
interface InterfaceA extends MyCallback {
public String abc() throws Exception;
}
class TestA implements InterfaceA {
#Override
public String abc() throws Exception {
return "abc";
}
#Override
public void callback(String value) {
System.out.println("value returned:" + value);
}
}
interface InterfaceB extends MyCallback {
public String xyz() throws Exception;
}
class TestB implements InterfaceB {
#Override
public String xyz() throws Exception {
return "xyz";
}
#Override
public void callback(String value) {
System.out.println("value returned:" + value);
}
}
You may try it like this:
public static void main(String[] args) throws InterruptedException {
Executors.newCachedThreadPool().invokeAll(Arrays.asList(
new Callable<String>() {
#Override public String call() { return new TestA().abc(); }
},
new Callable<String>() {
#Override public String call() { return new TestB().xyz(); }
}));
}
public interface InterfaceA {
public String abc() throws Exception;
}
public interface InterfaceB {
public String xyz() throws Exception;
}
class TestA implements InterfaceA {
#Override public String abc() {
System.out.println("Inside A"); return null;
}
}
class TestB implements InterfaceB {
#Override public String xyz() {
System.out.println("Inside B"); return null;
}
}

How to get Data from a Task in afterExecute of ScheduledThreadPoolExecutor

I'm using ScheduledThreadPoolExecutor and I don't know hot to deal with something.
I'm scheduling some tasks this way:
scheduledExecService = new ExtendedScheduledExecutor(numThreads, myThreadFactory);
TareaActualizacion act = new TareaActualizacion(inst);
ScheduledFuture<?> handle = scheduledExecService.scheduleWithFixedDelay(act, retrasoInicial, segundosRefresco, TimeUnit.SECONDS);
act is a Runnable class that recive some data by parameter:
public class TareaActualizacion implements Runnable {
private Instalacion instalacion;
public TareaActualizacion(Instalacion instalacion) {
this.instalacion = instalacion;
}
#Override
public void run() {
//Do something
}
public Instalacion getInstalacion() {
return instalacion;
}
}
Now in the afterExecute method of the ExtendedSecheduledExecutor I want to get the object Instalacion of the task TareaActualizacion but I don't know how to do it.
My ExtendedScheduledExecutor class looks like this:
public class ExtendedScheduledExecutor extends ScheduledThreadPoolExecutor{
public ExtendedScheduledExecutor(int arg0) {
super(arg0);
}
public ExtendedScheduledExecutor(int arg0, ThreadFactory arg1) {
super(arg0, arg1);
}
#Override
protected void afterExecute(Runnable r, Throwable t)
{
super.afterExecute(r, t);
System.out.println("Executing afterExecute. Throwable is " + t);
if (t != null)
t.printStackTrace();
//I need to get the Instalacion attribute from TareaActualizacion task. How can I do it??
}
}
Any idea of how can I solve it??
Thank you!
Neus
As Stephan already pointed out in https://stackoverflow.com/a/22145530 , you should try to decouple the scheduling and execution from the notification.
One approach for this could be to wrap the actual task (TareaActualizacion) into another implementation of the Runnable interface that only executes the actual task, and afterwards notifies a callback about the task that has been executed.
Depending on your precise requirements, there may be several degrees of freedom for the implementation, but a general approach could roughly look like this:
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduledTaskNotification
{
public static void main(String[] args) throws Exception
{
ScheduledExecutorService executor = Executors.newScheduledThreadPool(4);
int n = 3;
for (int i = 0; i < n; i++)
{
UpdateTask updateTask = new UpdateTask(i);
RunnableCallback<UpdateTask> callback = new RunnableCallback<UpdateTask>()
{
#Override
public void runnableFinished(UpdateTask updateTask)
{
System.out.println("Finished "+updateTask+", id "+updateTask.getID());
}
};
Runnable runnableWithCallback =
createRunnableWithCallback(updateTask, callback);
executor.scheduleWithFixedDelay(
runnableWithCallback, 1000, 200+i*200,
TimeUnit.MILLISECONDS);
}
}
static interface RunnableCallback<T extends Runnable>
{
void runnableFinished(T runnable);
}
private static <T extends Runnable> Runnable createRunnableWithCallback(
final T runnable, final RunnableCallback<T> callback)
{
return new Runnable()
{
#Override
public void run()
{
runnable.run();
callback.runnableFinished(runnable);
}
};
}
private static class UpdateTask implements Runnable
{
private final int id;
UpdateTask(int id)
{
this.id = id;
}
#Override
public void run()
{
System.out.println("Run "+this);
}
int getID()
{
return id;
}
#Override
public String toString()
{
return "UpdateTask "+id;
}
}
}
This is a bay way. You should not trying to get the result out of the Executor, because it is only responsible for scheduling and executing tasks, not whats happening inside of them.
Your TareaActualizacion runnable should post the result to another piece of code, where you need it. This can be achieved using a queue or in the easiest case SwingUtilities.invokeLater().

Categories