多线程操作方法

多线程操作方法在Thread类中定义.
线程命名与取得:
线程运行不确定性,所以线程名字是找寻线程的关键
Thread类中有提供线程名称的方法

  • 构造方法:public Thread​(Runnable target,String name)
  • 设置名字:public final void setName​(String name)
  • 取得名字:public final String getName​()

对于线程对象获得不能依靠this完成,因为线程状态不可控,但所有线程对象都会执行run()方法,因此可以在run()方法中获取当前线程,Thread类中提供有获取当前线程方法;public static Thread currentThread​();
线程对于匿名线程对象,会自动命名非重复线程名;

//使用静态全局变量实现线程自动命名;
    private static int threadInitNumber;
    private static synchronized int nextThreadNum() {
        return threadInitNumber++;
    }

    public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }

    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
        init(g, target, name, stackSize, null, true);
    }

在主方法中,调用线程类对象中的run()方法,发现主方法也是一个线程;进程为JVM,main为运行在JVM进程中的主线程,一台电脑可以运行若干个JVM进程;
主线程可以创建若干子线程,创建子线程,可以将一些复杂的逻辑和比较耗时逻辑交给子线程处理;

        new Thread(mt,"线程A").start();
        new Thread(mt).start();
        new Thread(mt,"线程B").start();
//        new Thread(mt).start();
//        new Thread(mt).start();
//        new Thread(mt).start();
        mt.run();

//answer
main
线程A
线程B
Thread-0

线程休眠
线程暂缓

//休眠为静态方法
public static void sleep​(long millis) throws InterruptedException
public static void sleep​(long millis,int nanos)throws InterruptedException

//InterruptedException是Exception子类,必须要处理
java.lang.Object
java.lang.Throwable
java.lang.Exception
java.lang.InterruptedException

public class viewSleep {
    public static void main(String[] args) throws Exception{
        new Thread(()->{
            for(int i=0;i<10;i++)
            {
                System.out.println(Thread.currentThread().getName()+" "+i);
                try{
                    //休眠1s,再重新执行;
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        },"线程对象").start();
    }
}

线程中断

public boolean isInterrupted​();//判断线程是否被中断
public void interrupt​();//中断线程执行

public class interruptCourrent {
    public static void main(String[] args) throws Exception{
        Thread thread=new Thread(()->{
            System.out.println("Too tired to work");
            try {
                Thread.sleep(10000);
                System.out.println("Get up to work");
            }catch (InterruptedException e)
            {
                System.out.println("老子宰了你");
            }
        });
        thread.start();//开始睡;
        Thread.sleep(1000);
        if(!thread.isInterrupted())
        {
            thread.interrupt();
            System.out.println("悄悄打扰一下");
        }
    }
}

线程强制执行

//使用join方法
public final void join​() throws InterruptedException

public class compelCournnce {
    public static void main(String[] args) throws Exception{
        Thread ma=Thread.currentThread();
        Thread thread=new Thread(()->{
                for(int i=0;i<100;i++)
                {
                    if(i>3)
                    {
                        try
                        {
                            ma.join();
                        }catch (InterruptedException e)
                        {
                            e.printStackTrace();
                        }
                    }
                    try
                    {
                        Thread.sleep(100);
                    }catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"执行 i= "+i);
                }
        },"子线程");

        thread.start();
        for(int i=0;i<100;i++)
        {
            Thread.sleep(100);
            System.out.println("【主线程】number= "+i);
        }
    }
}

线程礼让

public static void yield​()//礼让只会礼让一次当前资源

线程优先级(优先级越高,抢占资源可能性越高)

  • 设置优先级 public final void setPriority​(int newPriority)
  • 获取优先级 public final int getPriority​()
    优先级定义时都是通过int型数字完成,数字选择在Thread类有如下:
    静态成员:
    MAX_PRIORITY:最高优先级10
    MIN_PRIORITY:最低优先级1
    NORM_PRIORITY:中等优先级5
public class PriorityTest {
    public static void main(String[] args) throws Exception{
        Runnable run=()->{
            for(int i=0;i<10;i++)
            {
                System.out.println(Thread.currentThread().getName()+"执行");
            }
        };

        Thread threadA=new Thread(run,"线程对象A");
        Thread threadB=new Thread(run,"线程对象B");
        Thread threadC=new Thread(run,"线程对象C");
        threadA.setPriority(Thread.MAX_PRIORITY);
        threadB.setPriority(Thread.MIN_PRIORITY);
        threadC.setPriority(Thread.MIN_PRIORITY);
        threadA.start();
        threadB.start();
        threadC.start();
    }
}
//主线程优先级为5,匿名对象优先级为5;

猜你喜欢

转载自blog.csdn.net/qq_42378434/article/details/88771813