JAVA学习->线程的创建及线程中断

一、线程的创建

       JAVA中有三种创建线程的方法:一种是继承Thread;另一种是实现Runnable接口;还有一种是实现Callable接口

1、继承Thread创建线程

        继承Thread类,重写run()方法,run()方法代表线程要执行的任务。

        步骤:

                1、自定义MyThread类继承自Thread类;

              2、MyThread类里重写run()方法;

              3、创建MyThread的对象;

              4、启动线程。

例如

package cn.itcast_02;

public class MyThread extends Thread {
	public void run() {
		//一般用线程实现的,都是比较耗时的。
		for(int i=0;i<1000;i++) {
			System.out.println(i);
		}
	}
}
package cn.itcast_02;


public class MyThreadDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyThread mt=new MyThread();
		MyThread mt2=new MyThread();
		mt.start();
		mt2.start();
	}
}


2、实现Runnable接口创建线程

        实现Runnable接口,重写run()方法,run()方法代表线程要执行的任务。

        

步骤:

                1、自定义MyRunnable类实现自Runnable接口;

              2、MyRunnable类里重写run()方法;

              3、创建MyRunnable类的对象;

              4、创建Thread类的对象,并将3步骤的对象传给Thread构造方法作为参数;

              5、启动线程;

例如:

package cn.itcast_05;

public class MyRunnable implements Runnable {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0;i<1000;i++) {
			//由于实现接口的方式,就不可以直接使用Thread的方法,但可以间接地使用Thread.currentThread().getName()
			System.out.println(Thread.currentThread().getName()+":"+i);
		}
	}

}
package cn.itcast_05;

public class MyRunnableDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyRunnable mr=new MyRunnable();
		Thread th=new Thread(mr);
		Thread th2=new Thread(mr);
		th.start();
		th2.start();
	}

}

3、实现Callable接口

        实现callable接口,重写call()方法,call()作为线程的执行体,具有返回值,并且可以对异常进行声明和抛出。

创建和启动线程的步骤

        1.创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,且该call()方法有返回值,再创建Callable实现类的实例。(从java8开始,可以直接使用Lambda表达式创建Callable对象)。

        2.使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。

        3.使用FutureTask作为Thread对象的target创建并启动新线程。

        4.调用FutureTask对象的get方法来获得子线程执行结束后的返回值。

例如:

package cn.itcast_06;


import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;


class ThirdThread implements Callable<Integer>{
	public Integer call() {
		
		return null;
    }
}
public class CallableDemo {
    
    public static void main(String[] args) {
        //创建Callable对象
        ThirdThread rt=new ThirdThread();
        //先使用Lambda表达式创建Callable<Integer>对象,
        //并使用FutureTask来包装Callable对象
        FutureTask<Integer> task=new FutureTask<Integer>((Callable<Integer>)()->{
            int i=0;
            for(;i<1000;i++){
                System.out.println(Thread.currentThread().getName()+"===="+i);
            }
            //call()方法可以有返回值
            return i;
        });
        
        for(int i=0;i<1000;i++){
            System.out.println(Thread.currentThread().getName()+"===="+i);
            if(i==20){
                Thread t1=new Thread(task,"有返回值的线程");
                t1.start();
            }
        }
        try {
            System.out.println("子线程的返回值:"+task.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4、Java程序的运行原理

       由java命令启动JVM,JVM启动就相当于启动了一个线程,有该进程就创建了一个主线程去调用main方法。当然,JVM的启动是多线程的,因为它会在JVM启动时,也启动了垃圾回收进程(防止内存的溢出)。 


二、线程中断

1、API

void    interrupt ();

        向线程发送中断请求。线程的中断状态被设置成true,如果当前的线程被一个sleep调用阻塞,就会抛出InterruptedException异常。


static    boolean    interrupted  ();

           测试当线程(即正在执行这一命令的线程)是否中断。注意,这是一个静态方法,这一调用会产生副作用:它会将当前线程的中断状态重置为false。


boolean    isInterrupted    ();

          测试线程是否中断,不像静态的中断方法那样,这一调用方法不改变线程的中断状态。    

       

static    Thread    currentThread    ();

         返回代表当前执行线程的Thread对象。


例如:

package cn.itcast_07;

public class MyRunnable implements Runnable {

	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int i=0;i<1;i++) {
			//由于实现接口的方式,就不可以直接使用Thread的方法,但可以间接地使用Thread.currentThread().getName()
			System.out.println(Thread.currentThread().getName()+":"+i);
		}
	}

}
package cn.itcast_07;

import cn.itcast_05.MyRunnable;

public class InterruptedDemo {
	public static void main(String[] args) {
		MyRunnable mr=new MyRunnable();
		Thread th=new Thread(mr);
		Thread th2=new Thread(mr);
		th.start();
		th2.start();
		System.out.println(Thread.currentThread().isInterrupted());
		try {
			th.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(Thread.currentThread().isInterrupted());
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值