In the series of posts, I will present Java's threading APIs. Today's example is the simplest threading example using anonymous class in Java.
public class SimpleThread
{
public static void main(String[] args)
{
Thread thread1 = new Thread()
{
public void run()
{
int i = 0;
while (i < 10)
{
System.out.println(++i);
try
{
sleep(100);
}
catch (InterruptedException ie)
{
}
}
}
};
Thread thread2 = new Thread()
{
public void run()
{
int i = 0;
while (i < 10)
{
System.out.println(++i + 10);
try
{
sleep(100);
}
catch (InterruptedException ie)
{
}
}
}
};
thread1.start();
thread2.start();
}
}
To compile and run
$ javac SimpleThread.java && java SimpleThread
1
11
2
12
13
3
4
14
5
15
6
16
7
17
8
18
9
19
10
20
This example is easy enough and self-explanatory!
No comments:
Post a Comment