线程方法

线程

线程的状态

  1. 创建状态
  2. 就绪状态
  3. 运行状态
  4. 堵塞状态
  5. 死亡状态

线程的方法

线程停止

public class Stop implements Runnable{
	private boolean flag=true;
	
	
	
	public static void main(String[] args) {

		Stop thread=new Stop();
		
		new Thread(thread).start();
		
		for(int i=0;i<1000;i++){
			System.out.println(i);
			if(i==800){
			thread.stop();
			System.out.print("线程改结束了\n");
			}
		}
		
	}
	public void run() {

		
		while(flag){
			
			System.out.println("Run...");
			
		}

	}
	public void stop(){
		
		this.flag=false;
	}
}

线程停止

public class Join implements Runnable{

	public static void main(String[] args) throws InterruptedException {
		
		Join join=new Join();
		
		Thread thread=  new Thread(join);
		thread.start();
		
		for (int i =0; i < 200; i++) {
			
			if(i==150)thread.join();//尽量不要去使用,减少线程堵塞
			
			System.out.println("普通用户"+i);
			
		}

	}

	public void run() {
		
		for (int i = 0; i < 1000; i++) {
			System.out.println("ViP来了"+i);
			
		}
	}

}

线程礼让

public class Yield implements Runnable{

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Yield yield=new Yield();
         new Thread(yield,"a").start();
         
         new Thread(yield,"b").start();
         
	}
	public void run() {
		
		System.out.println(Thread.currentThread().getName()+"线程开始了");
		Thread.yield();//线程礼让  线程a退出CPU 再次与线程b竞争 礼让的成功与否还是在CPU
		System.out.println(Thread.currentThread().getName()+"线程结束了");
	}

}

线程休眠

Thread.sleep(1000)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值