多见线程方法
本节的类代码可以查看上一节的类代码
线程暂停
Thread.sleep(1000);//暂停1000毫秒
这就有点像在时间里面学习的*sleep()*函数了
package multiThread2;public class main {public static void main(String[] args) {Animal a1 = new Animal("张三",18);Animal a2 = new Animal("旺财",3);
// Thread t1 = new Thread(){
// public void run(){
// for (int i = 0; i < 10; i++) {
// System.out.println(a1);
// }
// }
// };
// t1.start();Thread t2 = new Thread(() -> {int second=0;for (int i = 0; i < 10; i++) {try {Thread.sleep(1000);
// System.out.println(a2);}catch (Exception e){e.printStackTrace();}System.out.println(second++);}});t2.start();}
}
加入到当前线程
t.join()
主要作用是将多个线程分开,成为多个进程,只有完成了前一个进程才能进行下一个进程
package multiThread2;public class main {public static void main(String[] args) throws InterruptedException {Animal a1 = new Animal("张三",18);Animal a2 = new Animal("旺财",3);Thread t1 = new Thread(){public void run(){for (int i = 0; i < 10; i++) {System.out.println(a1);}}};t1.start();t1.join();Thread t2 = new Thread(() -> {int second=0;for (int i = 0; i < 10; i++) {try {Thread.sleep(1000);System.out.println(a2);}catch (Exception e){e.printStackTrace();}System.out.println(second++);}});t2.start();}
}
这次图片有点大
线程的优先级
t.setPriority(int)
优先级从最大为10,一直到最小为1
为了方便,设计了
Thread.MAX_PRIORITY
Thread.MIN_PRIORITY
但是优先级只是一个相对的优先,优先级更大的只是更大几率占据了CPU的资源,而不是全部占据,这就导致可能优先级更低的线程会先进行完,
这也是它与join方法的主要区别
package multiThread2;public class main {public static void main(String[] args) throws InterruptedException {Animal a1 = new Animal("张三",18);Animal a2 = new Animal("旺财",3);Thread t1 = new Thread(() -> {for (int i = 0; i < 10; i++) {System.out.println(a1);}});Thread t2 = new Thread(() -> {for (int i = 0; i < 10; i++) {System.out.println(a2);}});t1.setPriority(Thread.MAX_PRIORITY);t2.setPriority(Thread.MIN_PRIORITY);t1.start();t2.start();}
}
临时暂停
t.yield();
当前线程,临时暂停,使得其他线程可以有更多的机会占用CPU资源
package multiThread2;public class main {public static void main(String[] args) throws InterruptedException {Animal a1 = new Animal("张三",18);Animal a2 = new Animal("旺财",3);Thread t1 = new Thread(() -> {for (int i = 0; i < 10; i++) {System.out.println(a1);}});Thread t2 = new Thread(() -> {for (int i = 0; i < 10; i++) {Thread.yield();System.out.println(a2);}});t1.start();t2.start();}
}
守护线程
t.setDaemon();
守护线程的概念是: 当一个进程里,所有的线程都是守护线程的时候,结束当前进程。
守护线程通常会被用来做日志,性能统计等工作。
这一节主要是Thread里面的一些方法,可以稍微记一下