Question :
public class Principal {
private static int x = 0;
private static int y = 0;
public static void sum() {
x = y + 1;
y = x + 1;
}
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
Thread a = new Thread() {
public void run() {
sum();
}
};
a.start();
Thread b = new Thread() {
public void run() {
sum();
}
};
b.start();
System.out.println(x);
}
}
}
How can I write this algorithm using node and javascript? I just do not have the slightest idea how to do it! I was analyzing some forms and found Web Worker
but could not do anything.
What should I do? I do not know how to work with threads on node, I tried to use this example node-threads-to-gogo but it seems that it does not run on windows.
Answer :
Javascript has no threads. However, you can perform asynchronous methods. Following example:
var x = 0;
var y = 0;
function sum() {
x = y + 1;
y = x + 1;
}
function main() {
for (i = 1; i <= 10; i++) {
var a = setTimeout(function run(){ sum() }, 0);
var b = setTimeout(function run(){ sum() }, 0);
}
console.log(x);
// Complementar: Valor de X depois de 1 segundo.
setTimeout(function(){ console.log(x); }, 1000);
}
main();
The result will be:
0 39
This happens because asynchronous methods are declared and ready for execution – but the scheduler does not invoke them until after the first console.log(x);
. The second console call is there to show the result after one second.
Javascript has some native methods that provide asynchronous mechanisms . Among them:
- setInterval
- setTimeout
- requestAnimationFrame
- XMLHttpRequest
- WebSocket
- Worker