Java中线程基础-线程再认识-线程的状态和Daemon线程

对Java里的线程再多一点点认识

线程常用方法和线程的状态

线程只有5种状态。整个生命周期就是这几种状态的切换。

run()和start() :run方法就是普通对象的普通方法,只有调用了start()后,Java才会将线程对象和操作系统中实际的线程进行映射,再来执行run方法。

yield() :让出cpu的执行权,将线程从运行转到可运行状态,但是下个时间片,该线程依然有可能被再次选中运行。

 类说明:start和run方法的区别

package com.xiangxue.ch1;

import com.xiangxue.tools.SleepTools;

/** 
 *
 *类说明:start和run方法的区别
 */
public class StartAndRun {
	//成员内部类
    public static class ThreadRun extends Thread{

        @Override
        public void run() {
            int i = 20;
            while(i>0){
            	SleepTools.ms(1000);
                System.out.println("I am "+Thread.currentThread().getName()
                		+" and now the i="+i--);
            }
        }
    }
    
    private static class User {
    	public void us() {
    		
    	}
    }

    public static void main(String[] args) {
    	ThreadRun beCalled = new ThreadRun();
    	beCalled.setName("BeCalled");
    	//beCalled.setPriority(newPriority);
    	beCalled.run();
    	
    	User user = new User();
    	user.us();
    	
    	//beCalled.start();
    }
}

sleep()工具类

package com.xiangxue.tools;

import java.util.concurrent.TimeUnit;

/**
 * 
 *
 *类说明:线程休眠辅助工具类
 */
public class SleepTools {
	
	/**
	 * 按秒休眠
	 * @param seconds 秒数
	 */
    public static final void second(int seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
        }
    }
    
    /**
     * 按毫秒数休眠
     * @param seconds 毫秒数
     */
    public static final void ms(int seconds) {
        try {
            TimeUnit.MILLISECONDS.sleep(seconds);
        } catch (InterruptedException e) {
        }
    }
}

线程的优先级

取值为1~10,缺省为5,但线程的优先级不可靠,不建议作为线程开发时候的手段

守护线程

和主线程共死,finally不能保证一定执行。

Daemon线程

package com.xiangxue.ch1;

import java.util.concurrent.ExecutionException;

/**
 *
 *  类说明:守护线程的使用和守护线程中的finally语句块
 */
public class DaemonThread {
	//内部类
	private static class UseThread extends Thread {
		@Override
		public void run() {
			try {
				while (!isInterrupted()) {
					System.out.println(Thread.currentThread().getName()
							+ " I am extends Thread.");
				}
				System.out.println(Thread.currentThread().getName() 
						+ " interrupt flag is " + isInterrupted());
			} finally {
				System.out.println(".....................finally");
			}
		}
	}

	public static void main(String[] args) throws InterruptedException, ExecutionException {		
		UseThread useThread = new UseThread();
		//useThread.setDaemon(true);//设置成Daemon线程
		useThread.start();
		Thread.sleep(100); //ms
		useThread.interrupt();
	}
}

发布了132 篇原创文章 · 获赞 21 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_40993412/article/details/104143396