互联网JAVA面试常问问题(二)

一、线程有几种创建方式?

这是一道比较常见的java线程问题,一般就是两种线程创建方式:

  • 继承Thread类
  • 实现Runnable接口

继承Thread类

public class MyThread extends Thread{
    private String name;

    public MyThread(String name) {
        this.name = name;
    }

    public void run() {
        for (int i = 0; i < 5; ++i) {
            System.out.println(name + " 运行,i=" + i);
        }
    }
}

class ThreadDemo{
    public static void main(String[] args) {
        MyThread m1 = new MyThread("线程1");
        MyThread m2 = new MyThread("线程2");

        m1.start();
        m2.start();
    }
}

实现Runnblae接口

class MyRunnable implements Runnable {
    private String name;

    public MyThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        for (int i = 0; i < 5; ++i) {
            System.out.println(name + " 运行,i=" + i);
        }
    }
}

class RunnableDemo {
    public static void main(String[] args) {
        MyThread m1 = new MyThread("线程1");
        MyThread m2 = new MyThread("线程2");

        Thread t1 = new Thread(m1); // 实例化Thread类对象
        Thread t2 = new Thread(m2);

        t1.start(); // 启动多线程
        t2.start();
    }
}

结果:多个线程交替执行,执行结果每次都不会一样

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

从Thread类的定义可以发现,Thread也是Runnable接口的子类,但是Thread类并没有实现Runnable接口的run()方法,下面是Thread类的定义:

Private Runnable target; 
public Thread(Runnable target,String name){ 
    init(null,target,name,0); 
} 
private void init(ThreadGroup g,Runnable target,String name,long stackSize){ 
    ... 
    this.target=target; 
} 
public void run(){ 
    if(target!=null){ 
        target.run(); 
    } 
}

从定义中可以发现,在 Thread 类中的 run() 方法调用的是 Runnable 接口中的 run() 方法,也就是说此方法是由 Runnable 子类完成的,所以如果要通过继承 Thread 类实现多线程,则必须覆写 run()。

相比较而言Runnable()接口实现更好,因为实现接口的方式比继承类的方式更加灵活,也能减少程序减少程序之间的耦合度。如果一个类继承Thread类,则不适合于多个线程共享资源,而实现了 Runnable 接口,就可以方便的实现资源的共享。

二、start()方法和run()方法的区别?
  • 只有调用了start()方法,才会表现出多线程的特性,不同线程里面的run()方法里面的代码交替执行。
  • 只是调用run()方法,那么代码还是会同步执行,必须等待一个线程的run()方法里面的代码全部执行完毕后,另一个线程才可以执行run()方法里面的代码。
三、Runnable接口和Callable接口的区别?
  • Runnable接口中的run()方法的返回值是void,它就是纯粹执行run()方法中的代码而已
  • Callable接口中的call()方法是有返回值的,该返回值的类型是一个泛型号,和Future、FutureTask配合使用,可以获取异步执行结果。
四、线程的状态有哪些?

要想实现多线程,必须在主线程中创建新的线程对象。任何线程一般具有5种状态,即创建,就绪,运行,阻塞,终止。下面分别介绍一下这几种状态:

  • 创建状态

在程序中用构造方法创建了一个线程对象后,新的线程对象便处于新建状态,此时它已经有了相应的内存空间和其他资源,但还处于不可运行状态。新建一个线程对象可采用Thread 类的构造方法来实现,例如 “Thread thread=new Thread()”。

  • 就绪状态

新建线程对象后,调用该线程的 start() 方法就可以启动线程。当线程启动时,线程进入就绪状态。此时,线程将进入线程队列排队,等待 CPU 服务,这表明它已经具备了运行条件。

  • 运行状态

当就绪状态被调用并获得处理器资源时,线程就进入了运行状态。此时,自动调用该线程对象的 run() 方法。run() 方法定义该线程的操作和功能。

  • 阻塞状态

一个正在执行的线程在某些特殊情况下,如被人为挂起或需要执行耗时的输入/输出操作,会让 CPU 暂时中止自己的执行,进入阻塞状态。在可执行状态下,如果调用sleep(),suspend(),wait() 等方法,线程都将进入阻塞状态,发生阻塞时线程不能进入排队队列,只有当引起阻塞的原因被消除后,线程才可以转入就绪状态。

  • 死亡状态

线程调用 stop() 方法时或 run() 方法执行结束后,即处于死亡状态。处于死亡状态的线程不具有继续运行的能力。

五、Java 程序每次运行至少启动几个线程?

至少启动两个线程,每当使用 Java 命令执行一个类时,实际上都会启动一个 JVM,每一个JVM实际上就是在操作系统中启动一个线程,Java 本身具备了垃圾的收集机制。所以在 Java 运行时至少会启动两个线程,一个是 main 线程,另外一个是垃圾收集线程。

6、线程操作的方法?
  • 线程的强制运行

在线程操作中,可以使用join()方法让一个线程强制运行,线程强制运行期间,其他线程无法运行,必须等待此线程完成之后才可以继续执行。

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

class ThreadJoinDemo{
    public static void main(String[] args) {
        MyThreadJoin myThreadJoin = new MyThreadJoin();
        Thread t = new Thread(myThreadJoin, "线程");
        t.start();
        for(int i =0; i < 5; ++i){
            if(i > 2){
                try {
                    t.join(); // 线程强制运行
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("Main线程运行:"+i);
        }
    }
}

运行结果

Main线程运行:0
Main线程运行:1
Main线程运行:2
线程 运行,i=0
线程 运行,i=1
线程 运行,i=2
线程 运行,i=3
线程 运行,i=4
Main线程运行:3
Main线程运行:4
  • 线程休眠

在程序中允许一个线程进行暂时的休眠,直接使用 Thread.sleep() 即可实现休眠。这个线程操作在其他例子中有用到。

  • 线程中断

当一个线程运行时,另外一个线程可以直接通过interrupt()方法中断其运行状态。

public class MyThreadInterrput implements Runnable{
    public void run(){
        System.out.println("1、进入run()方法") ;
        try{
            Thread.sleep(10000) ;   // 线程休眠10秒
            System.out.println("2、已经完成了休眠") ;
        }catch(InterruptedException e){
            System.out.println("3、休眠被终止") ;
            return ; // 返回调用处
        }
        System.out.println("4、run()方法正常结束") ;
    }
};
class ThreadInterruptDemo{
    public static void main(String args[]){
        MyThreadInterrput mt = new MyThreadInterrput() ;
        Thread t = new Thread(mt,"线程");
        t.start() ; // 启动线程
        try{
            Thread.sleep(2000) ;    // 线程休眠2秒
        }catch(InterruptedException e){
            System.out.println("5、休眠被终止") ;
        }
        t.interrupt() ; // 中断线程执行
    }
};

执行结果

1、进入run()方法
3、休眠被终止
  • 后台线程

在 Java 程序中,只要前台有一个线程在运行,则整个 Java 进程都不会消失,所以此时可以设置一个后台线程,这样即使 Java 线程结束了,此后台线程依然会继续执行,要想实现这样的操作,直接使用 setDaemon() 方法即可。

public class MyThreadDeamon implements Runnable{
    @Override
    public void run() {
        while (true){
            System.out.println(Thread.currentThread().getName() + "正在运行");
        }
    }
};

class ThreadDaemonDemo{
    public static void main(String[] args) {
        MyThreadDeamon myThreadDeamon = new MyThreadDeamon();
        Thread thread = new Thread(myThreadDeamon, "线程");
        thread.setDaemon(true);
        thread.start();
    }
}

尽管run()是while无限循环,但是程序依旧可以执行完,因为无限循环已经设置为后置执行。

  • 线程的优先级

在 Java 的线程操作中,所有的线程在运行前都会保持在就绪状态,那么此时,通过setPriorit()设置优先级, 哪个线程的优先级高,哪个线程就有可能会先被执行。

public class MyThreadPriority  implements Runnable{
    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) ;  
        }
    }
};
 class ThreadPriorityDemo{
    public static void main(String args[]){
        Thread t1 = new Thread(new MyThreadPriority(),"线程A") ; 
        Thread t2 = new Thread(new MyThreadPriority(),"线程B") ; 
        Thread t3 = new Thread(new MyThreadPriority(),"线程C") ; 
        t1.setPriority(Thread.MIN_PRIORITY) ;   // 优先级最低
        t2.setPriority(Thread.MAX_PRIORITY) ;   // 优先级最高
        t3.setPriority(Thread.NORM_PRIORITY) ;  // 优先级最中等
        t1.start() ;    
        t2.start() ;    
        t3.start() ;    
    }
};

执行结果

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

从程序的运行结果中可以观察到,线程将根据其优先级的大小来决定哪个线程会先运行,但是需要注意并非优先级越高就一定会先执行,哪个线程先执行将由 CPU 的调度决定。

  • 线程的礼让

在线程操作中,也可以使用 yield() 方法将一个线程的操作暂时让给其他线程执行

public class MyThreadYield implements Runnable{
    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().getName()+"礼让:") ;
                Thread.currentThread().yield() ;    // 线程礼让
            }
        }
    }
};
class ThreadYieldDemo{
    public static void main(String args[]){
        MyThreadYield my = new MyThreadYield() ;
        Thread t1 = new Thread(my,"线程A") ;
        Thread t2 = new Thread(my,"线程B") ;
        t1.start() ;
        t2.start() ;
    }
}; 

执行结果

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

点我关注

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值