Thread类常用方法

Thread类构造方法:

1.Thread();

2.Thread(String name);

3.Thread(Runable r);

4.Thread(Runable r, String name);

public class Test {

	public static void main(String[] args) {
		/*
		MyThread thread1 = new MyThread();
		MyThread thread2 = new MyThread("MyThread");
		thread1.start();
		thread2.start();
		*/
		MyRunnable run = new MyRunnable();
		Thread thread3 = new Thread(run);
		Thread thread4 = new Thread(run, "MyThread");
		thread3.start();
		thread4.start();
	}

}

常用方法:

start();//启动线程

getId();//获得线程ID

getName();//获得线程名字

getPriority();//获得优先权

isAlive();//判断线程是否活动

isDaemon();//判断是否守护线程

getState();//获得线程状态

sleep(long mill);//休眠线程

join();//等待线程结束

yield();//放弃cpu使用权利

interrupt();//中断线程

currentThread();//获得正在执行的线程对象


守护线程:也叫精灵线程,当程序只剩下守护线程的时候就会退出。

守护线程 的作用类似在后台静默执行,比如JVM的垃圾回收机制,这个就是一个守护线程。而非守护线程则不会。

MyRunnable run = new MyRunnable();
		Thread thread3 = new Thread(run);
		Thread thread4 = new Thread(run, "MyThread");
		//设置优先级别
//		thread3.setPriority(1);
//		thread3.setPriority(Thread.MAX_PRIORITY);
//		thread4.setPriority(10);
		thread3.setPriority(Thread.NORM_PRIORITY);
		thread4.setPriority(Thread.NORM_PRIORITY);
		//获得线程的优先级别
		System.out.println(thread3.getPriority());
		System.out.println(thread4.getPriority());
		System.out.println("----------------------");
		thread3.start();
		thread4.start();
		System.out.println("----------------------");
		System.out.println("线程3是否活动:"+thread3.isAlive());
		System.out.println("线程4是否活动:"+thread4.isAlive());
		System.out.println("----------------------");
//		thread3.setDaemon(true);//设置为守护线程,必须在启动之前设置
		System.out.println("线程3是否是守护线程:"+thread3.isDaemon());
		System.out.println("线程4是否是守护线程:"+thread4.isDaemon());
		System.out.println("----------------------");
		//获取线程状态
		System.out.println("线程3的状态:"+thread3.getState());
		System.out.println("线程4的状态:"+thread4.getState());
		try {
			thread4.join();//等待线程4的结束
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值