java : anonymous class - java

In java this is valid
new Thread(new Runnable()
{
public void run()
{
for(int i=0;i<5;i++)
System.out.println("From anonymous:"+i);
}
}
).start();
But this is not :
Thread t=new Thread(new Runnable()
{
public void run()
{
for(int i=0;i<5;i++)
System.out.println("From anonymous:"+i);
}
}
).start();
can I achieve it with anonymous class? If yes then How

Your code does not work, because it wants to assign the result of the start() method to the variable t. You can do it like so:
Thread t=new Thread(new Runnable()
{
public void run()
{
for(int i=0;i<5;i++)
System.out.println("From anonymous:"+i);
}
}
);
t.start();

Also, in this case you don't need to use Runnable interface because is implemented by the Thread class.
new Thread() {
#Override
public void run() {
for(int i=0;i<5;i++)
System.out.println("From anonymous:"+i);
}
}.start();

One thing to note here is that the start method of Thread returns void. This is why you cannot assign it to a variable.

Related

How to check for functionalty with multiple threads working without synchronization

Consider this code:
public class test2 {
public static void main(String[] args) throws Exception{
Thread t1 = new Thread(new Runnable() {
public void run() {
for(int i = 0; i<1000000; i++) {
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
Out.println("Counter" +" "+ i);
}
});
t1.start();
t2.start();
}
}
This code is susposed to complete this task:
Implement a program in which a thread increments a counter (static field) 1000000 times. Another thread should immediately output the same counter without waiting for the end of the first thread.
Is my code right? The reason why I am asking is because the output is always 0,and I am not sure if that is right.I'm confused as how to check for functionalty of a code when there is no synchronization in play.
The problem is that your code is missing the required static field (e.g. i in the code given below).
class Main {
// Counter
static int i = 0;
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(new Runnable() {
public void run() {
for (i = 0; i < 1000000; i++) {
}
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
System.out.println("Counter" + " " + i);
}
});
t1.start();
t2.start();
}
}
Output:
Counter 8588

Hot to use Thread in JAVA for EWS API?

I have below function for EWS JAVA API.
public static void cleanRootFolders(String account) throws Exception{
deleteEmailsFromInbox(account);
deleteEmailsFromDrafts(account);
deleteEmailsFromSentItems(account);
deleteEmailsFromJunkEmails(account);
deleteEventsFromCalendar(account);
deleteEmailsFromDeletedItems(account);
}
How can i Implement Thread for performing this Six methods simultaneously for saving the time instead of one after one ?
You can use a thread pool as follows:
ExecutorService executor = Executors.newFixedThreadPool(6);
Runnable r = new Runnable() {
#Override
void run() {
deleteEmailsFromInbox(account);
}
}
executor.execute(r)
r = new Runnable() {
#Override
void run() {
deleteEmailsFromDrafts(account);
}
}
executor.execute(r)
Or you could simply start a thread for each of the tasks:
Runnable r = new Runnable() {
#Override
void run() {
deleteEmailsFromInbox(account);
}
}
(new Thread(r)).start();
Below is complete code:
public static void cleanRootFolders(String account) throws Exception{
/*create number of threads = number of cores. Do note, creating 6 threads doesn't mean 6 threads will work simultaneously.*/
ExecutorService executor = Executors.newFixedThreadPool(numberOfCores);
executor.execute(new Runnable() {
public void run() {
deleteEmailsFromInbox(account);
}
});
executor.execute(new Runnable() {
public void run() {
deleteEmailsFromDrafts(account);
}
});
executor.execute(new Runnable() {
public void run() {
deleteEmailsFromSentItems(account);
}
});
executor.execute(new Runnable() {
public void run() {
deleteEmailsFromJunkEmails(account);
}
});
executor.execute(new Runnable() {
public void run() {
deleteEventsFromCalendar(account);
}
});
executor.execute(new Runnable() {
public void run() {
deleteEmailsFromDeletedItems(account);
}
});
executor.shutdown();
//always shutdown, so the threads do not keep running.
}

Cannot name background thread, Void error

I am trying to name my thread, I have this code
public void DownloadFromUrl(final String fileName) { //this is the downloader method
new Thread(new Runnable() {
public void run() {
Looper.prepare();
...
but when I try to name it like this
public void DownloadFromUrl(final String fileName) { //this is the downloader method
Thread t1 = new Thread(new Runnable() {
public void run() {
Looper.prepare();
...
it just says
Required: Java.lang.Thread
Found: Void
Maybe you called the start method on the thread. This returns void.
Try this instead.
Thread t1 = new Thread(new Runnable() {
public void run() {
Looper.prepare();
...
}
t1.start();
But I agree with the other answer, you probably should use somethine else other than threads.
try to use AsynkTask for downloading instead of thread
Look as this AsynkTask

Java 8 Timer to repeat one function

How can I implement a timer in Java 8? I prefer one simple method for this. I want to do something every 15 min or 30 min. Any idea?
you can use
Thread.sleep(milliseconds)
call the function you want and put it inside Runnable .
Example :
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(3000); // 3
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//your Function
}
});
}
}).start();
OR
Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
}});
t.start();

thread and creating object

I am trying to learn about thread and find some examples in the internet. This is a java class that output "hello, world" every 3 seconds. But I have a feeling that the part about creating a Runable object is redundant.
Instead of writing
Runnable r = new Runnable(){ public void run(){...some actions...}};
Can I put the method run() somewhere else for easy reading?
This is what I have:
public class TickTock extends Thread {
public static void main (String[] arg){
Runnable r = new Runnable(){
public void run(){
try{
while (true) {
Thread.sleep(3000);
System.out.println("Hello, world!");
}
} catch (InterruptedException iex) {
System.err.println("Message printer interrupted");
}
}
};
Thread thr = new Thread(r);
thr.start();
}
And this is what I want to accomplish
public static void main (String[] arg){
Runnable r = new Runnable() //so no run() method here,
//but where should I put run()
Thread thr = new Thread(r);
thr.start();
}
Can I put the method run() somewhere else for easy reading?
Yes you could create your own runnable like this
public class CustomRunnable implements Runnable{
// put run here
}
and then
Runnable r = new CustomRunnable () ;
Thread thr = new Thread(r);
From the Java threads tutorial, you can use a slightly different style:
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();
}
}
Just make your anonymous Runnable class an inner static class, like so:
public class TickTock {
public static void main (String[] arg){
Thread thr = new Thread(new MyRunnable());
thr.start();
}
private static class MyRunnable implements Runnable {
public void run(){
try{
while (true) {
Thread.sleep(3000);
System.out.println("Hello, world!");
}
} catch (InterruptedException iex) {
System.err.println("Message printer interrupted");
}
}
}
}
Or since TickTock already extends Thread in your example code, you can just override its run method:
public class TickTock extends Thread {
public static void main (String[] arg){
Thread thr = new TickTock();
thr.start();
}
#Override
public void run(){
try{
while (true) {
Thread.sleep(3000);
System.out.println("Hello, world!");
}
} catch (InterruptedException iex) {
System.err.println("Message printer interrupted");
}
}
}

Categories