目录
优先级别
1.同优先级别的线程,就是先运行先得到服务,采用时间片策略
2.如果优先级别高,被cpu调度的概率就高
3.级别:1--10,默认为5,1-10,数值越大优先级别越高
public class TestThread01 extends Thread {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("tt1" + i);
}
}
}
class TestThread02 extends Thread {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("tt2" + i);
}
}
}
class Test{
public static void main(String[] args) {
// 创建两个子线程来争抢资源
TestThread01 tt1 = new TestThread01();
tt1.setPriority(10);
tt1.start();
TestThread02 tt2 = new TestThread02();
tt2.setPriority(1);
tt2.start();
}
}
join()
当线程调用了一个join(),这个线程就会被先执行,结束后才去执行其余的线程
注意:必须先start(),再join()
public class TestThreadMethod extends Thread{
public TestThreadMethod() {
}
public TestThreadMethod(String name) {
super(name);
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(this.getName() + "---" + i);
}
}
}
@Test
public void testJoin() throws InterruptedException {
TestThreadMethod ttm = new TestThreadMethod("子线程");
for (int i = 0; i < 20; i++) {
// 当main方法这个程序运行到i == 10,子线程开始运行,main方法进入阻塞状态
if(i == 10){
ttm.start();
ttm.join();// 半路劫杀,使程序进入阻塞状态,结束后程序转变为就绪状态
}
// 子线程结束运行后,i=10才开始输出,main方法开始继续运行
System.out.println(i);
}
}
/*
8
9
子线程---0
子线程---1
子线程---2
子线程---3
子线程---4
子线程---5
子线程---6
子线程---7
子线程---8
子线程---9
10
11
*/
sleep(long mmillis):
人为的使程序进入阻塞状态,使程序停止运行一段时间
@Test
public void sleepTest01() throws InterruptedException {
long startTime = System.currentTimeMillis();
Thread.sleep(3000);
long endTime = System.currentTimeMillis();
System.out.println(endTime - startTime);
}
// 3011:是因为程序运行也需要0.011秒
经典秒表案例:
@Test
public void sleepTest02() throws InterruptedException {
DateFormat df = new SimpleDateFormat("HH:mm:ss");
while (true){
Date d = new Date();
Thread.sleep(1000);
System.out.println(df.format(d));
}
}
/*
11:44:16
11:44:17
11:44:18
11:44:19
*/
setDaemon():
设置伴随线程:主线程和子线程一起运行的同时,若主线程停止,则子线程也立刻停止
@Test
public void setDaemonTest(){
TestThreadMethod ttm = new TestThreadMethod("子线程");
ttm.setDaemon(false);
ttm.start();
for (int i = 0; i < 10; i++) {
System.out.println("主线程的---" + i);
}
}