进程:系统资源分配的单位;
线程:处理器任务调度和执行的的单位,线程之间共享进程资源。
学习大纲:
常用方法:
1.getName():返回当前线程的名字2.setName():修改线程名字;有两种方法:2.1.直接在start()开启线程前,修改;2.2.使用Thread类的有参构造;3.currentThread():返回当前线程对象4.yield():线程让步,让CPU把资源分配给下一个线程;注意,也有让步完线程后又抢到了CPU资源5.sleep(longmillstime):设置线程的等待时间,如果调用该方法线程会等待设置的毫秒值的时间后在运行(用于跨年倒计时~) 6.join():线程阻塞,就是线程插队;在线程a中,让调用线程b的join(),则线程a会等待线程b执行完毕后在运行7.isAlive():判断当前线程是否存活8.start():开启线程9.run():书写线程的执行内容10.stop():已弃用,直接结束线程
线程优先级:
11.getPriority():获取当前线程的优先级12.setPriority():修改当前线程的优先级线程中优先级的问题:*MAX_PRIORITY:10*MIN_PRIORITY:1*NORM_PRIORITY:5*设置优先级:*1.设置优先级:setPriority() *2.获取优先级:getPriority() *注意:并不一定设置了最高的优先级就一定要执行完毕后,在执行优先级较低的线程。
//演示publicclassDemoThreadMethod { publicstaticvoidmain(String[] args) { //使用有参构造修改线程名字MyThread02mt=newMyThread02("Thread_00"); // mt.setName("Thread_01");//修改线程的优先级mt.setPriority(Thread.MAX_PRIORITY); mt.start(); //输出0-100之内的奇数for (inti=0; i<100; i++) { if (i%2!=0) { //直接只用线程名调用需要使用的方法Thread.currentThread().setName("Main主线程"); System.out.println(Thread.currentThread().getName() +"__"+Thread.currentThread().getPriority() +":"+i); } Thread.currentThread().setPriority(Thread.NORM_PRIORITY); // if (i == 3)// Thread.currentThread().yield();/*if (i == 15) {try {mt.join();} catch (InterruptedException e) {e.printStackTrace();}}if (i == 33) {try {Thread.currentThread().sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}*/ } booleanalive=mt.isAlive(); System.out.println(alive); } } classMyThread02extendsThread{ publicvoidrun() { //输出0-100之内的偶数for (inti=0; i<100; i++) { if (i%2==0) //1.currentThread()方法是静态的所以可以直接使用类名调用//2.当前类继承了Thread类,this指代了当期类,所以可以直接使用this调用currentThread()方法,或者省略this关键字System.out.println(currentThread().getName()+"__"+Thread.currentThread().getPriority() +":"+i); } } //使用有参构造器修改线程的名字publicMyThread02(Stringname) { super(name);//把值传给父类中值 } }
生命周期:
现在先了解,知道概括的五个生命周期中的状态即可。
Thread类底层定义的各种生命周期中的状态,以及触发的方法...
欢迎关注微信公众号:小红的成长日记,一起学Java!