zoukankan      html  css  js  c++  java
  • Java多线程系列2 线程常见方法介绍

    守护线程 执行一些非业务方法,比如gc。当全部都是守护线程的时候,jvm退出

    线程优先级  设置线程优先级:setPriority(int priorityLevel)。参数priorityLevel范围在1-10之间,值越大优先级越高,

            能被执行到的概率越大,但非优先执行。

    sleep() 让当前的正在执行的线程暂停指定的时间,并进入阻塞状态 时间到了,恢复到就绪状态

    join() 等待线程结束,我执行完了 你才能执行

    public class TestJoin {
    
    	public static void main(String[] args) throws Exception {
    		Thread thread1 = new Thread(new PrintThread("t1"));
    		
    		Thread thread2 = new Thread(new PrintThread("t2"));
    		thread1.start();
    		thread1.join(); //我执行完了你才能执行
    		thread2.start();
    	        thread2.join();
    
    	}
    
    }
    
    class PrintThread implements Runnable {
    	private String name;
         
    	public PrintThread(String name) {
    
    		this.name = name;
    	}
    
    	@Override
    	public void run() {
    		for (int i = 0; i < 3; i++) {
    			try {
    				Thread.sleep(100);
    			} catch (InterruptedException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    			System.out.println(name);
    		}
    
    	}
    
    }
    

      

      运行效果如下

        

    yield() 谦让,我暂时不执行,我回到就绪状态

          另外 yield()方法还与线程优先级有关,当某个线程调用yiled()方法从运行状态转换到就绪状态后,CPU从就绪状态线程队列中只会选择与该线程优先级相同或优先级更高的线程去执行。但是分配还是随机的 可能还是执行到原来的线程。

  • 相关阅读:
    一个菜鸟把Vue项目打包为APP的道路
    echarts
    no module named selenium
    git使用教程
    JDK安装与环境变量配置
    家具摆件
    家店分会场
    双十一电器城
    室内门锁
    http://cjy.suda.edu.cn/File.aspx?id=427
  • 原文地址:https://www.cnblogs.com/javabigdata/p/6826597.html
Copyright © 2011-2022 走看看