• 线程状态


    new创建一个线程之后进入新生状态

    调用start方法进入就绪状态

    获得cpu时间片进入运行状态

    (在这个时间片运行完进入死亡状态

    (在这个时间片结束后没有运行完就进入挂起状态也就是就绪状态,系统此时运行其他程序)

    停止线程

    1.自然终止:线程体正常执行完毕

    2.外部干涉:

    1)线程类中,定义线程体使用的标识

    2)线程体使用该标识

    3) 提供对外方法用来改变该标识

    4) 外部根据条件调用该方法

     阻塞线程

    1.join :合并线程(将多条路合并到一条路上,多个个线程和并成一个线程)

    join()   -----》等待该线程的终止

    package thread;
    //join阻塞
    public class Join阻塞 {
    	public static void main(String[] args) throws InterruptedException {
    		Thread1 s= new Thread1();
    		Thread demo1=new Thread(s);
    		demo1.start();
    		
    		
    		for(int i=0;i<100;i++){
    			if(50==i){
    				demo1.join();
    			}
    			System.out.println("main"+i);
    		}
    	}
    }
    class Thread1 implements Runnable{
    	@Override
    	public void run() {
    		// TODO Auto-generated method stub
    			for(int i=0;i<100;i++){
    			System.out.println("study thread..."+i);
    		}
    			
    		
    	}
    
    	
    
    }
    

     study thread...95
    study thread...96
    study thread...97
    study thread...98
    study thread...99
    main50
    main51
    main52
    main53
    main54

    先将join的线程执行完再结束;

    yield:让步   是一个静态方法 (让出cpu的调度,即暂停本线程)

    但是cpu可能重新调度到该线程,也就是没有严格意义上的暂停,不准确

    sleep:休眠   sleep(多少毫秒)

    休眠的时候不释放锁,

    与时间相关,1用于模拟倒计时,2模拟网络延时

    package thread;
    //模拟数数
    public class 模拟数数 { public static void main(String[] args) throws InterruptedException { int num=10; while(true){ if(num==0){break;} System.out.println(num); num--; Thread.sleep(1000); } } }

     模拟倒计时

    package thread;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    //方便共享资源
    public class 倒计时 {
    	public static void main(String[] args) throws InterruptedException {
    		Date endTime = new Date(System.currentTimeMillis()+10*1000);
    		long end= endTime.getTime();
    		
    	
    		while(true){
    			System.out.println(new SimpleDateFormat("mm:ss").format(endTime));
    			endTime =new Date(endTime.getTime()-1000);
    			Thread.sleep(1000);
    			if(end-10000>endTime.getTime()){
    				break;
    			}
    		}
    	}		
    		
    
    
    }
    
  • 相关阅读:
    vuejs2从入门到精通视频教程
    vuejs2项目开发实战视频教程
    vuejs2从入门到精通视频教程
    Bootstrap视频教程
    开通博卡拉
    阿里云Ubuntu 16 FTP安装配置注意事项
    [解决方法] Java-Class.forName() 反射/映射子类 并转化为父类/接口
    [HTML/CSS] ul元素居中处理
    [HTML/Javascript] JS判断IE浏览器各版本
    [HTML/JS] JQuery 页面滚动回到顶部
  • 原文地址:https://www.cnblogs.com/tianhao/p/4192024.html
Copyright © 2020-2023  润新知