Java多线程常用操作方法

By AverageJoeWang
 标签:

线程休眠

  • 方法
public static native void sleep(long millis) throws InterruptedException;

sleep()时间以后然后再开始就绪。
sleep()方法是一个静态方法,也就是说他只对当前对象有效

  • 实例
public class RunnableTest implements Runnable{
    public void run(){
        for (int i = 0; i < 1000; i++){
            try {
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "、x=" + i);
        }
    }

    public static void main(String[] args){
        RunnableTest runnableTest1 = new RunnableTest();
        new Thread(runnableTest1).start();
        new Thread(runnableTest1).start();
        new Thread(runnableTest1).start();
    }
}

线程优先级

  • 方法
public final void setPriority();
public final int getPriority();

确定优先级可以通过Thread类的几个常量来决定,主方法是中等优先级

  • 最高优先级:Thread.MAX_PRIORITY,1
  • 中等优先级:Thread.NORM_PRIORITY,5
  • 最低优先级:Thread.MIN_PRIORITY,10

  • 实例

public class RunnableTest implements Runnable{
    public void run(){
        for (int i = 0; i < 20; i++){
            System.out.println(Thread.currentThread().getName() + "、x=" + i);
        }
    }

    public static void main(String[] args){
        RunnableTest runnableTest1 = new RunnableTest();
        Thread t1 = new Thread(runnableTest1, "线程a");
        Thread t2 = new Thread(runnableTest1, "线程b");
        Thread t3 = new Thread(runnableTest1, "线程c");
        t1.setPriority(Thread.MIN_PRIORITY);
        t2.setPriority(Thread.NORM_PRIORITY);
        t3.setPriority(Thread.MAX_PRIORITY);
        t1.start();
        t2.start();
        t3.start();
    }
}