多线程一、基础API

  1. 继承Thread类创建线程
public class MyThread extends Thread{
	@Override
	public void run(){
		super.run();
		System.out.println("MyThread");
	}

	public static void main(String[] args){
		MyThread myThread = new MyThread();
		// 启动线程的方法,调用start()方法,不是直接调用run()方法
		myThread.start();
		System.out.println("运行结束!");
	}
} 
  1. 实现Runnable接口创建线程
public class MyRunnable implements Runnable{
	@Override
	public void run(){
		System.out.println("运行中!");
	}

	public static void main(String[] args){
		Runnable runnable = new MyRunnable();
		Thread thread = new Thread(runnable);
		thread.start();
		System.out.println("运行结束!");
	}
}
  1. currentThread()方法
    currentThread()方法可返回代码段正在被哪个线程调用的信息。
public class MyThread extends Thread{
	public MyThread(){
		System.out.println("构造方法的打印: " + Thread.currentThread().getName());
	}
	
	public void run(){
		System.out.println("run方法的打印:" + Thread.currentThread().getName());
	}
	
	public static void main(String[] args){
		MyThread myThread = new MyThread();
		myThread.start();
		//MyThread.run();
	}
}
// 调用start()方法的输出结果:
构造方法的打印: main
run方法的打印: Thread-0
// 调用ru()方法的输出结果:
构造方法的打印: main
run方法的打印: main
  1. isAlive()方法
    isAlive()方法的功能是判断当前的线程 是否处于活动状态。
    活动状态就是线程已经启动且尚未终止。线程处于正在运行或准备开始运行的状态,就认为线程是“存活”的。
public class MyThread extends Thread{
	@Override
	public void run(){
		System.out.println("run = " + this.isAlive());
	}

	public static void main(String[] args) throws Exception {
		MyThread myThread = new MyThread();
		System.out.println("begin = " + myThread.isAlive());
		myThread.start();
		// myThread.sleep(1000L);
		System.out.println("end = " + myThread.isAlive());
	}
}
// 注释掉sleep()方法输出结果:
begin = flase
end = true
run = true
// 放开注释输出结果:
begin = false
run = true
end = false
myThread对象已经在一秒内执行完成,所以在之后查询的时候是false
  1. sleep()方法
    方法sleep()的作用是在指定的毫秒数内让当前“正在执行的线程”休眠(暂停执行)。这个“正在执行的线程”是指this.currentThread()返回的线程。
public class MyThread extends Thread{
	@Override
    public void run() {
        try{
            System.out.println("run threadName = " + this.currentThread().getName() + "begin");
            Thread.sleep(2000L);
            System.out.println("run threadName = " + this.currentThread().getName() + "end");
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyThread mythread = new MyThread();
        System.out.println(System.currentTimeMillis());
        mythread.run();
        System.out.println(System.currentTimeMillis());
    }
}
  1. getId()方法
    getId()方法的作用是取得线程的唯一标识。
public class MyThread {
    public static void main(String[] args) {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() + " " + thread.getId());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值