后台线程:次要的线程
Thread类提供的相关方法:setDaemon(boolean on) :将该线程标记为后台线程或用户线程
setDaemon(true):为后台线程 setDaemon(false):为用户线程
getName(): 返回该线程的名称 setName(String name): 改变线程名称,使之与参数name
相同,
后台线程是不受重视的,当主线程和子线程都执行结束时,后台线程也就随之结束了尽管可能没达到指定的要求
线程优先级
线程优先级用数字来表示,范围从1到10
主线程的缺省优先级为5,子线程的优先级默认与其父线程相同
Thread类提供的相关方法:
getPriority() 返回线程的优先级。返回值为int setPriority(int newPriority) 更改线程的优先级。
package com.demo; public class lzwCode { public static void main(String[] args) { MyThreadA myA = new MyThreadA(); Thread thA = new Thread(myA); thA.setName("线程A"); thA.setPriority(10); thA.start(); MyThreadB myB = new MyThreadB(); Thread thB = new Thread(myB); thB.setDaemon(true); thB.setName("后台线程"); thA.setPriority(1); thB.start(); for (int i = 0; i < 10; i++) { String s = Thread.currentThread().getName(); System.out.println(s + "==" + i); } System.out.println("主线程结束!"); } } class MyThreadA implements Runnable { public void run() { for (int i = 0; i < 10; i++) { String s = Thread.currentThread().getName(); System.out.println(s + "-->" + i); } } } class MyThreadB implements Runnable { public void run() { for (int i = 0; i < 5; i++) { String s = Thread.currentThread().getName(); System.out.println(s + "==>" + i); } } }控制台结果:
在java程序中,只要前台有一个线程在运行,整个java程序进程不会消失,所以此时可以设置一个后台线程,这样即使java进程消失了,此后台线程依然能够继续运行,大家不要误以为优先级越高就先执行。谁先执行还是取决于谁先去的CPU的资源、
public class lzwCode implements Runnable { public void run() { while (true) { System.out.println(Thread.currentThread().getName() + "在运行"); } } public static void main(String[] args) { lzwCode lc = new lzwCode(); Thread th = new Thread(lc, "线程A"); th.setDaemon(true); th.start(); } }
线程的礼让
在线程操作中,也可以使用yield()方法,将一个线程的操作暂时交给其他线程执行
package com.demo; public class lzwCode implements Runnable { public void run() { for (int i = 0; i < 5; ++i) { System.out.println(Thread.currentThread().getName() + "运行" + i); if (i == 3) { System.out.println("线程的礼让"); Thread.currentThread().yield(); } } } public static void main(String[] args) { Thread th1 = new Thread(new lzwCode(), "A"); Thread th2 = new Thread(new lzwCode(), "B"); th1.start(); th2.start(); } }
A运行0
A运行1
A运行2
A运行3
线程的礼让
A运行4
B运行0
B运行1
B运行2
B运行3
线程的礼让
B运行4