Reputation: 41
Is it possible to have a loop run, say checking if a movement of a mouse has occurred, while the program is running another loop to do something else. I know that I can have the loops inside of each other but that is not efficient enough for my program to recognize the movement of the mouse as it would take about 30 minutes in my program for any change to occur.
Just in case I am not being clear on my question... I am asking if two loops can occur in the same class at the same time without interfering with each other.
Upvotes: 2
Views: 78
Reputation: 201447
Yes. And, here is an example -
public static class Test implements Runnable {
public Test(String name) {
this.name = name;
}
private String name;
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + ": " + i);
System.out.flush();
}
}
}
public static void main(String[] args) {
Thread a = new Thread(new Test("A"));
Thread b = new Thread(new Test("B"));
b.start();
a.start();
System.out.println("Mainly 1");
try {
b.join();
a.join();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("Mainly 2");
}
}
Which will probably output a slight variation of my test results which were
B: 0 Mainly 1 A: 0 B: 1 B: 2 A: 1 B: 3 B: 4 A: 2 A: 3 A: 4 Mainly 2
Upvotes: 5
Reputation: 21047
What you need is to perform concurrent "processes" (more precisely, threads). Check The Java Tutorials: Concurrency.
Quoting from the tutorial:
Computer users take it for granted that their systems can do more than one thing at a time. They assume that they can continue to work in a word processor, while other applications download files, manage the print queue, and stream audio. Even a single application is often expected to do more than one thing at a time. [...] Software that can do such things is known as concurrent software.
The Java platform is designed from the ground up to support concurrent programming, with basic concurrency support in the Java programming language and the Java class libraries. Since version 5.0, the Java platform has also included high-level concurrency APIs.
Upvotes: 3