|
a command line
free external tools,
java sources
cpp sources
articles
|
How to create one or more threads in Java with a few lines of code. Free source code examples with simple instant solutions.
starting point: a simple java program, having just one thread - the main thread.
public class csj01x1
{
public static void main(String args[]) throws Throwable
{
new csj01x1().myfunc();
}
void myfunc() throws Throwable
{
for (int i=0; i<100; i++) {
System.out.println("thread "
+Thread.currentThread().getName()+" step "+i);
Thread.sleep(500);
}
}
}
output:
thread main step 0 thread main step 1 thread main step 2 thread main step 3 ...solution 01: creating two parallel threads by implementing the Runnable interface, i.e. adding a "run" method.
public class csj01x2 implements Runnable
{
public static void main(String args[]) throws Throwable
{
csj01x2 obj1 = new csj01x2();
csj01x2 obj2 = new csj01x2();
new Thread(obj1).start();
new Thread(obj2).start();
// main thread is ending here,
// Thread-0 and Thread-1 continue to run.
}
public void run()
{
try {
for (int i=0; i<100; i++) {
System.out.println("thread "
+Thread.currentThread().getName()+" step "+i);
Thread.sleep(500);
}
} catch (Throwable t) { }
}
}
output:
thread Thread-0 step 0 thread Thread-1 step 0 thread Thread-0 step 1 thread Thread-1 step 1 thread Thread-0 step 2 thread Thread-1 step 2 thread Thread-0 step 3 thread Thread-1 step 3 ...
public class csj01x3 extends Thread
{
public static void main(String args[]) throws Throwable
{
new csj01x3().start();
new csj01x3().start();
// main thread is ending here,
// Thread-0 and Thread-1 continue to run.
}
public void run()
{
try {
for (int i=0; i<100; i++) {
System.out.println("thread "
+Thread.currentThread().getName()+" step "+i);
Thread.sleep(500);
}
} catch (Throwable t) { }
}
}
this produces the same output as solution 01, but it has one tradeoff: as we derive our class from Thread, we can no longer derive it from anything else. therefore solution 01 is more flexible.
|
|