Use the Java Thread class to demonstrate the following funct
Use the Java Thread class to demonstrate the following functionalities:
(1)
Create five threads; show the id for each thread – getId()
(2)
Show the use of the following methods (be creative in your code):
start(), sleep(), yield(), getState(), setName(), getName(),
setPriority(), getPriority() -- Make sure to show threads are processed
with different priority (be creative)
* As a minimum, discuss the conditions resulted from exceptions – examine the Throws section of each method, to base your code discussions.
Solution
//start(), sleep(), yield(), setName(), setPriority(),
class Demo implements Runnable
{
public void run()
{
//Thread State
Thread.State state = Thread.currentThread().getState();
//Thread ID
System.out.println(\"Thread Id = \" + Thread.currentThread().getId());
//Thread Name
System.out.println(\"Thread Name = \" + Thread.currentThread().getName());
//Thread Priority
System.out.println(\"Thread Priority = \" + Thread.currentThread().getPriority());
//Thread State Display
System.out.println(\"Thread State = \" + state);
//Yields the current thread
Thread.yield();
//Exception handling
try
{
//Takes the thread to sleep
Thread.sleep(2000);
}
catch(InterruptedException ie)
{
System.out.println(Thread.currentThread());
}
}
}
public class threadDemo
{
public static void main(String ss[])
{
//Creates 5 objects
Demo td1 = new Demo();
Demo td2 = new Demo();
Demo td3 = new Demo();
Demo td4 = new Demo();
Demo td5 = new Demo();
//Creates 5 threads and assigns object to it
Thread t1 = new Thread(td1);
Thread t2 = new Thread(td2);
Thread t3 = new Thread(td3);
Thread t4 = new Thread(td4);
Thread t5 = new Thread(td5);
//Sets the name and priority of each thread
t1.setName(\"First\"); t1.setPriority(3);
t2.setName(\"Second\"); t2.setPriority(6);
t3.setName(\"Third\"); t3.setPriority(8);
t4.setName(\"Fourth\"); t4.setPriority(1);
t5.setName(\"Fifth\"); t4.setPriority(2);
//Stats each thread
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
Output
Thread Id = 12
Thread Name = Third
Thread Priority = 8
Thread State = RUNNABLE
Thread Id = 14
Thread Id = 11
Thread Name = Fifth
Thread Name = Second
Thread Priority = 5
Thread Id = 13
Thread Id = 10
Thread Priority = 6
Thread State = RUNNABLE
Thread Name = First
Thread Priority = 3
Thread State = RUNNABLE
Thread Name = Fourth
Thread State = RUNNABLE
Thread Priority = 2
Thread State = RUNNABLE

