java基础的核心技术:多线程(二)

本文介绍了Java中Thread类的常用方法,包括线程的启动、执行、优先级设置等,并详细解释了线程间的通信机制及优先级调度策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Thread类的常用方法

package com.attest.java1;

/*
 * Thread的常用方法
 * 1.start(),启动线程并执行相应的run()方法
 * 2.run():子线程要执行的代码放入run()方法中
 * 3.currentThread():静态的,调取当前的线程
 * 4.getName():获取此线程的名字
 * 5.setName():设置此线程的名字
 * 6.yield(): 调用此方法的线程释放当前CPU的执行权
 * 7.join():在A线程中调用B线程的join()方法。
 * 表示:当执行到此方法。A线程停止执行,直至B线程执行完毕,A线程再接着执行jonin()之的的代码执行
 * 8.isAlive():判断当前纯种是否还存活
 * 9.sleep(long millis): 显示的让当前线程眨眼1毫秒
 * 10.线程通信 : wait()	notify()	notifyAll()
 * 
 * 11.设置线程的优先级
 * 	getPriority(): 返回线程的优先级
 * 	setPriority(int newPriority) : 改变线程的优先级
 * 	线程创建时继承父线程的优先级
 */
class SubThread1 extends Thread {

	@Override
	public void run() {
		for (int i = 0; i <= 100; i++) {
//			try {
//				/*
//				 * 方法重写的规则 :子类的方法不能比父类抛更大的异常 ,而在这Thread父类里,
//				 * 根本就没有抛出异常
//				 */
//				Thread.currentThread().sleep(1000);//为什么 这个异常不能使用Throws
//				
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			System.out.println(Thread.currentThread().getName() + " : " +Thread.currentThread().getPriority() +" : "+ i);
		}
	}

}

public class TestThread1 {

	public static void main(String[] args) {
		SubThread1 st1 = new SubThread1();
		st1.setName("子线程1");
		st1.setPriority(Thread.MAX_PRIORITY);//可以写数字
		st1.start();
		Thread.currentThread().setName("=========主线程");
		for (int i = 0; i <= 100; i++) {
			System.out.println(Thread.currentThread().getName() + " : " +Thread.currentThread().getPriority() +" : "+ i);
			// if(i % 10 ==0){//当 i 是10的倍数时
			// Thread.currentThread().yield();//强制释放当前CPU的执行权
			// }
			if (i == 20) {
				try {
					st1.join();//强制让st1线程执行进来。只有当st1线程执行完,才可以执行其他线程。这里指的是主线程
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		System.out.println(st1.isAlive());//判断当前(st1)纯种是否还存活

	}

}



---------------------------------------------------------------------------------------------

线程的优先级(线程的调度)

* 调度的策略

-->时间片

-->抢占式:高优先级的纯种抢占CPU

* Java的调度方法

-->同优先级的线程组成先进先出队列(先到先服务),使用时间片策略

-->对高优先级,使用优先调度的抢占式策略


线程的优先级

* 线程的优先级控制

》MAX_PRIORITY(10 )

》MIN_PRIORITY(1 )

》NORM_PRIORITY(5 )

* 涉及的方法

》getPriority():返回线程的优先级

》setPriority(int newPriority) :改变线程的优先级

》线程创建时继承父线程的优先级

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值