Java线程常用方法

  • .start()方法和run()方法

写一个新的线程的时候,都需要重写run方法。但是重写run方法之后并不代表就创建了新的线程。要想启动一个新的线程必须调用start()方法来启动线程。如果直接调用run方法则并没有新的线程产生。此时的run方法和普通的方法一样。

  • 线程的休眠:sleep()

线程休眠顾名思义就是让线程停止运行一会。

例子:

class Thread1 implements Runnable{

    @Override
    public void run() {
        for(int i=0;i<3;i++){
            try {
                // 单位是毫秒
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()
                    + "运行,i = " + i) ;    // 取得当前线程的名字
        }
    }
}

public class ExerciseDemo1 {

    public static void main(String[] args) {
        Thread1 mt = new Thread1() ;    // 实例化Runnable子类对象
        Thread t = new Thread(mt);// 启动线程
        t.start();

    }

}

结果:

Thread-0运行,i = 0
Thread-0运行,i = 1
Thread-0运行,i = 2

结果会每隔一秒出打印一次。

 

  • 当前线程:CurrentThread()

该方法是返回当前正在执行线程的对象的引用。

例:

class Thread1 implements Runnable{

    @Override
    public void run() {
        for(int i=0;i<3;i++){
            System.out.println(Thread.currentThread().getName()
                    + "运行,i = " + i) ;    // 取得当前线程的名字
        }
    }
}

public class ExerciseDemo1 {

    public static void main(String[] args) {
        Thread1 mt = new Thread1() ;    // 实例化Runnable子类对象
        new Thread(mt,"线程1").start() ;        // 启动线程
        mt.run() ;    // 直接调用run()方法
    }

}

结果:因为线程的运行抢到CPU的概率是一样的,所以结果的顺序可能不是一成不变的。

main运行,i = 0
main运行,i = 1
main运行,i = 2
线程1运行,i = 0
线程1运行,i = 1
线程1运行,i = 2

可以看出这里有两个线程一个是主线程,线程名字是main。另一个是我们自己创建的线程,名字是线程1。

“线程1”是我们自己创建的线程,而“main”线程是jvm在启动的时候创建的线程。(jvm在启动的时候不止创建了“main”线程,这里就不介绍了)。并且结果中的main线程是因为直接调用了run方法才打印出来的。也证明了如果直接调用run方法是不会创建新的线程的。而结果中的线程1是我们自己创建的线程,并且用start方法启动之后打印出来的。

 

  • 判断线程是否在执行:isAlive()

class Thread1 implements Runnable{

    @Override
    public void run() {
        for(int i=0;i<3;i++){
            System.out.println(Thread.currentThread().getName()
                    + "运行,i = " + i) ;    // 取得当前线程的名字
        }
    }
}

public class ExerciseDemo1 {

    public static void main(String[] args) {
        Thread1 mt = new Thread1() ;    // 实例化Runnable子类对象
        Thread t = new Thread(mt);// 启动线程
        System.out.println("线程开始之前--------" + t.isAlive());
        t.start();
        System.out.println("线程开始之后--------" + t.isAlive());
        // 让main方法休眠1秒,让创建的线程运行完毕
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程运行完毕之后--------" + t.isAlive());

    }

}

      因为创建的线程比较简单,所以main线程休眠1秒之后很大概率创建的线程就运行完毕了。但是如果创建的线程比较复杂可能1秒就不太够,这里只是做个例子。

结果:

线程开始之前--------false
线程开始之后--------true
Thread-0运行,i = 0
Thread-0运行,i = 1
Thread-0运行,i = 2
线程运行完毕之后--------false

从结果可以很明显的看出,在启动之前该线程是没有在执行的。start之后线程开始执行,执行完毕之后,线程就会销毁所以也是false。

 

  • 线程强制运行:join()

先执行调用该方法的线程,知道运行完毕。

例:

class Thread1 implements Runnable{

    @Override
    public void run() {
        for(int i=0;i<30;i++){
            System.out.println(Thread.currentThread().getName()
                    + "线程运行 -->  " + i) ;    // 取得当前线程的名字
        }
    }
}

public class ExerciseDemo1 {

    public static void main(String[] args) {
        Thread1 mt = new Thread1() ;    // 实例化Runnable子类对象
        Thread t = new Thread(mt);// 启动线程
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 10; i++) {
            System.out.println("Main线程运行 --> " + i) ;
        }

    }

}

结果:

Thread-0线程运行 -->  0
Thread-0线程运行 -->  1
Thread-0线程运行 -->  2
Thread-0线程运行 -->  3
Thread-0线程运行 -->  4
Thread-0线程运行 -->  5
Thread-0线程运行 -->  6
Thread-0线程运行 -->  7
Thread-0线程运行 -->  8
Thread-0线程运行 -->  9
Thread-0线程运行 -->  10
Thread-0线程运行 -->  11
Thread-0线程运行 -->  12
Thread-0线程运行 -->  13
Thread-0线程运行 -->  14
Thread-0线程运行 -->  15
Thread-0线程运行 -->  16
Thread-0线程运行 -->  17
Thread-0线程运行 -->  18
Thread-0线程运行 -->  19
Thread-0线程运行 -->  20
Thread-0线程运行 -->  21
Thread-0线程运行 -->  22
Thread-0线程运行 -->  23
Thread-0线程运行 -->  24
Thread-0线程运行 -->  25
Thread-0线程运行 -->  26
Thread-0线程运行 -->  27
Thread-0线程运行 -->  28
Thread-0线程运行 -->  29
Main线程运行 --> 0
Main线程运行 --> 1
Main线程运行 --> 2
Main线程运行 --> 3
Main线程运行 --> 4
Main线程运行 --> 5
Main线程运行 --> 6
Main线程运行 --> 7
Main线程运行 --> 8
Main线程运行 --> 9

 

 

  • 线程的中断:interrupt()

一个线程可以被另一个线程中断其操作的状态,使用 interrupt()方法完成。

class Thread1 implements Runnable{

    @Override
    public void run() {

        System.out.println("1.-------进入run方法");

        try {
            Thread.sleep(10000);
            System.out.println("2.-------线程休眠结束");
        } catch (InterruptedException e) {
            System.out.println("3.-------线程休眠终止");
            // 如果不加"4.-------线程正常结束"就会打印出来,但是线程并不是正常结束的。
            return;
        }
        System.out.println("4.-------线程正常结束");
    }
}

public class ExerciseDemo1 {

    public static void main(String[] args) {
        Thread1 mt = new Thread1() ;    // 实例化Runnable子类对象
        Thread t = new Thread(mt);// 启动线程
        t.start();
        try{
            Thread.sleep(2000) ;    // 线程休眠2秒
        }catch(InterruptedException e){
            System.out.println("3、休眠被终止") ;
        }
        t.interrupt() ;    // 中断线程执行

    }

}

结果:

1.-------进入run方法
3.-------线程休眠终止

 

 

  • 后台线程:setDaemon()

将此线程标记为守护线程或用户线程。 当运行的线程都是守护进程线程时,Java虚拟机将退出。

class Thread1 implements Runnable{

    @Override
    public void run() {
        int i=0;
        //设置死循环,这样来实现线程不断运行,设置后台运行。
        while(true){
            System.out.println(Thread.currentThread().getName() + "在运行。"+i) ;
        }
    }
}

public class ExerciseDemo1 {

    public static void main(String[] args) {
        Thread1 mt = new Thread1() ;    // 实例化Runnable子类对象
        Thread t = new Thread(mt,"线程");// 启动线程
        t.setDaemon(true) ;    // 此线程在后台运行
        t.start() ;    // 启动线程

    }

}

此时创建的线程不会一直运行,而是主线程结束之后,该线程也会结束运行。

 

  • 线程的优先级:getPriority()

返回此线程的优先级。

优先级分为最低,最高,普通三个(Thread.MIN_PRIORITY,Thread.MAX_PRIORITY,Thread.NORM_PRIORITY)

设置优先级为:setPriority()

例:

class Thread1 implements Runnable{

    @Override
    public void run() {
        for(int i=0;i<5;i++){
            try{
                Thread.sleep(500) ;    // 线程休眠
            }catch(InterruptedException e){}
            System.out.println(Thread.currentThread().getName()
                    + "运行,i = " + i) ;    // 取得当前线程的名字
        }
    }
}

public class ExerciseDemo1 {

    public static void main(String[] args) {
        Thread t1 = new Thread(new Thread1(),"线程A") ;    // 实例化线程对象
        Thread t2 = new Thread(new Thread1(),"线程B") ;    // 实例化线程对象
        Thread t3 = new Thread(new Thread1(),"线程C") ;    // 实例化线程对象
        t1.setPriority(Thread.MIN_PRIORITY) ;    // 优先级最低
        t2.setPriority(Thread.MAX_PRIORITY) ;    // 优先级最高
        t3.setPriority(Thread.NORM_PRIORITY) ;    // 优先级一般
        t1.start() ;    // 启动线程
        t2.start() ;    // 启动线程
        t3.start() ;    // 启动线程
    }

}

结果:

线程C运行,i = 0
线程A运行,i = 0
线程B运行,i = 0
线程C运行,i = 1
线程B运行,i = 1
线程A运行,i = 1
线程A运行,i = 2
线程C运行,i = 2
线程B运行,i = 2
线程B运行,i = 3
线程C运行,i = 3
线程A运行,i = 3
线程B运行,i = 4
线程A运行,i = 4
线程C运行,i = 4

主方法的优先级:

    public static void main(String args[]){
        System.out.println("主方法的优先级:" + 
            Thread.currentThread().getPriority()) ;    // 取得主方法的优先级
        System.out.println("MAX_PRIORITY = " + Thread.MAX_PRIORITY) ;
        System.out.println("NORM_PRIORITY = " + Thread.NORM_PRIORITY) ;
        System.out.println("MIN_PRIORITY = " + Thread.MIN_PRIORITY) ;
    }
主方法的优先级:5
MAX_PRIORITY = 10
NORM_PRIORITY = 5
MIN_PRIORITY = 1

由此可知,主方法优先级是5,也就是普通优先级,而且主方法是一个线程对象。

 

  • 线程的礼让:yield()

例:

class Thread1 implements Runnable{

    @Override
    public void run() {
        for(int i=0;i<5;i++){
            try{
                Thread.sleep(500) ;//休眠一下
            }catch(Exception e){}
            System.out.println(Thread.currentThread().getName()
                    + "运行,i = " + i) ;    // 取得当前线程的名字
            if(i==2){
                System.out.print("线程礼让:") ;
                Thread.currentThread().yield() ;    // 首先获取当前线程,然后线程礼让
            }
        }
    }
}

public class ExerciseDemo1 {

    public static void main(String[] args) {
        Thread1 my = new Thread1() ;    // 实例化MyThread对象
        Thread t1 = new Thread(my,"线程A") ;
        Thread t2 = new Thread(my,"线程B") ;
        t1.start() ;
        t2.start() ;
    }

}

 

结果:

线程A运行,i = 0
线程B运行,i = 0
线程B运行,i = 1
线程A运行,i = 1
线程B运行,i = 2
线程A运行,i = 2
线程礼让:线程礼让:线程A运行,i = 3
线程B运行,i = 3
线程A运行,i = 4
线程B运行,i = 4

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java多线程常用方法有以下几种: 1. 继承Thread类:创建一个继承自Thread类的子类,并重写run()方法,在run()方法中定义线程要执行的任务。然后通过创建子类的对象,调用start()方法启动线程。 2. 实现Runnable接口:创建一个实现了Runnable接口的类,并实现其run()方法,在run()方法中定义线程要执行的任务。然后通过创建该类的对象,将其作为参数传递给Thread类的构造方法,再调用start()方法启动线程。 3. 使用Callable和Future:Callable接口是一种带有返回值的线程,通过实现Callable接口并实现其call()方法来定义线程要执行的任务。然后使用ExecutorService的submit()方法提交Callable任务,并返回一个Future对象,通过Future对象可以获取线程执行的结果。 4. 使用线程池:通过Executor框架提供的线程池来管理线程的创建和执行。可以使用Executors类提供的静态方法创建不同类型的线程池,然后将任务提交给线程池执行。 5. 使用synchronized关键字:通过在方法或代码块前加上synchronized关键字来实现线程同步,保证多个线程对共享资源的访问是互斥的。 6. 使用Lock接口:Lock接口提供了比synchronized更灵活和强大的线程同步机制。通过Lock接口的lock()和unlock()方法来实现对共享资源的加锁和解锁。 7. 使用wait()、notify()和notifyAll()方法:通过Object类提供的wait()、notify()和notifyAll()方法来实现线程间的通信和协作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值