Web Development, SEO, Social Media, Software & Database Development
Java Simple Thread Example
//AUTHOR : THE JAVA GEORDIE
// SIMPLE THREAD EXAMPLE
import java.util.Random;
class Apple implements Runnable
{
String name; // GIVE THREAD A NAME
int time; // SET A TIME FOR THREAD TO SLEEP
Random r = new Random();
//BUILD CONSTRUCTOR
public Apple(String s)
{
name =s; // SET NAME OF THREAD
time = r.nextInt(999);//DEFINE A RANDOM TIME
}
public void run()
{
try
{
System.out.printf("%s is sleep for %d\n",name,time);
Thread.sleep(time);
System.out.printf("%s is done.\n",name);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
---------------------------------
class start
{
public static void main(String args[])
{
//CREATE THREADS
Thread t1= new Thread(new Apple("one"));
Thread t2= new Thread(new Apple("two"));
Thread t3= new Thread(new Apple("three"));
//START THREADS
t1.start();
t2.start();
t3.start();
}
}
------------OUTPUT-----
one is sleep for 67
three is sleep for 288
two is sleep for 724
one is done.
three is done.
two is done.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment