Java – Set Thread Priority

[code lang=”java”]public class Main {
public static void main(String[] args)
throws Exception {
Thread thread1 = new Thread(new TestThread(1));
Thread thread2 = new Thread(new TestThread(2));
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("The priority has been set.");
}
}[/code]

Java – Daemon Thread

[code lang=”java”]class MyDaemon implements Runnable {
Thread thrd;
MyDaemon() {
thrd = new Thread(this);
thrd.setDaemon(true);
thrd.start();
}
public boolean isDaemon(){
return thrd.isDaemon();
}
public void run() {
try {
while(true) {
System.out.print(".");
Thread.sleep(100);
}
}
catch(Exception exc) {
System.out.println("MyDaemon interrupted.");
}
}
}

public class Main {
public static void main(String args[]) throws Exception{
MyDaemon dt = new MyDaemon();
if(dt.isDaemon())
System.out.println("dt is a daemon thread.");

Thread.sleep(10000);
System.out.println("\nMain thread ending.");
}
}[/code]

Java – Create Thread by Implementing Runnable Interface

[code lang=”java”]class MyThread implements Runnable {
int count;

MyThread() {
count = 0;
}
public void run() {
System.out.println("MyThread starting.");
try {
do {
Thread.sleep(500);
System.out.println("In MyThread, count is " + count);
count++;
} while (count < 5);
} catch (InterruptedException exc) {
System.out.println("MyThread interrupted.");
}
System.out.println("MyThread terminating.");
}
}

class RunnableDemo {
public static void main(String args[]) {
System.out.println("Main thread starting.");
MyThread mt = new MyThread();
Thread newThrd = new Thread(mt);
newThrd.start();
do {
System.out.println("In main thread.");
try {
Thread.sleep(250);
} catch (InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
} while (mt.count != 5);

System.out.println("Main thread ending.");
}
}[/code]