1)join线程
可以使用join()将一个大问题划分为若干小问题,每一个小问题分配一个线程。当执行该方法时,调用线程将被阻塞,直到被加入的线程执行结束再执行调用线程。
public class JoinThread extends Thread {
public JoinThread(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName() + " " + i);
}
}
public static void main(String[] args) throws InterruptedException {
new JoinThread("new Thread").start();
for (int i = 0; i < 100; i++) {
if (i == 20) {
JoinThread jt = new JoinThread("Joined Thread");
jt.start();
jt.join();
}
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}2)Daemon线程
Daemon线程是守护线程,比如JVM的垃圾回收线程,如果前台线程都死亡了,它也会死亡。前台线程创建的线程默认也是前台线程,后台线程创建的线程默认是后台线程,可以通过setDaemon()进行更改。
public class DaemonThread extends Thread {
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(getName() + " " + i);
}
}
public static void main(String[] args) {
DaemonThread t = new DaemonThread();
t.setDaemon(true);
t.start();
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}3)线程睡眠
public class SleepTest {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " " + i);
Thread.sleep(1000);
}
}
}执行上面代码每隔1s输出一次。
4)线程让步
当某个线程调用yield()方法后,该线程将进入到就绪状态,与比该线程优先级更高或者相同的线程争夺cpu资源,而比其优先级低的线程并不会得到cpu资源。在多cpu环境下,yield()方法有时候效果不是很理想,基于可移植性的考虑,不建议使用yield()。
public class YieldTest extends Thread {
public YieldTest(String name) {
super(name);
}
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(getName() + " " + i);
if (i == 20) {
Thread.yield();
}
}
}
public static void main(String[] args) {
YieldTest yt1 = new YieldTest("superior thread");
YieldTest yt2 = new YieldTest("primary thread");
yt1.setPriority(Thread.MAX_PRIORITY);
yt2.setPriority(Thread.MIN_PRIORITY);
yt1.start();
yt2.start();
}
}
京公网安备 11010502036488号