天天看点

线程常用api线程api

标题

  • 线程api
    • 常用线程api方法
    • 使用方法 --继承
    • 使用方法 --实现
    • 使用join ---- join()

线程api

常用线程api方法

方法 名称
start() 启动线程
currentThread() 获取当前线程对象
getId() 获取当前线程id
getName() 获取当前线程名称
sleep() 休眠线程
stop() 停止线程 --不安全 --不推荐使用
setDaemon() 改变线程状态:true-守护线程:flase-非守护线程
join() 线程执行优先级

使用方法 --继承

class CreateThread extends Thread{
	@Override
	public void run(){
		//使用sleep()进行休眠
		try{
			//休眠一秒以后,在执行
			Thread.sellp(1000);
			//也可以 this.sellp(1000)
		}

		//子线程
		System.out.println("getId:"+getId())//获取线程id
		
			
		System.out.println("getName:"+getName())//获取线程名称
	}
}



public class ThreadDemo{
	public static void main(String[] args){
		//获取主线程对象 currentThread()
		System.out.println(Thread.currentThread());
		//获取主线程id
		System.out.println(Thread.currentThread().getId());
		//获取主线程名称
		System.out.println(Thread.currentThread().getName());

		CreateThread createThread = new CreateThread();
		Thread thread = new Thread(createThread);
		thread.setDaemon(true);//改变用户线程为守护线程
		//thread.setDaemon(false);//非守护线程
		thread.start();
	}

}

           

使用方法 --实现

class CreateThread implements Runnable{
	@Override
	public void run(){
		//使用sleep()进行休眠
		try{
			//休眠一秒以后,在执行
			Thread.currentThread().sellp(1000);
			//也可以 this.sellp(1000)
		}

		//子线程
		System.out.println("getId:"+Thread.currentThread().getId())//获取线程id

			
		System.out.println("getName:"+Thread.currentThread().getName())//获取线程名称
	}
}



public class ThreadDemo{
	public static void main(String[] args){
		//获取主线程对象 currentThread()
		System.out.println(Thread.currentThread());
		//获取主线程id
		System.out.println(Thread.currentThread().getId());
		//获取主线程名称
		System.out.println(Thread.currentThread().getName());
		
		CreateThread createThread = new CreateThread();
		Thread thread = new Thead(createThread,"子线程");
		thread .start();
	}

}

           

使用join ---- join()

public class ThreadDemo{
	public static void main(String[] args){
		Thread t1 = Thread(new Runnable(){
			@Override
			public void run(){
				System.out.println("t1");
			}
		});
	
		Thread t2 = Thread(new Runnable(){
			@Override
			public void run(){
				System.out.println("t2");
			}
		});

		t1.start();
		t2.start();
		
		//join() 可以指定线程的执行循序
		try{
			//这样可以让t1线程先执行,t1执行完毕后,在执行t2
			t1.join();
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}
}