初探Java多线程

什么是多线程?这些话就不说了,直接看例子。

一、  使用多线程

1、  继承Thread类

package com.ztz.myThread;

public class MyThread extends Thread{
	@Override
	public void run() {
		System.out.println("继承Thread");
	}
	public static void main(String[] args)throws Exception {
		MyThread t=new MyThread();
		t.start();
	}
}

2、  实现Runnable接口

package com.ztz.myThread;

public class MyRunnable implements Runnable{
	@Override
	public void run() {
		System.out.println("实现Runnable接口");
	}
	public static void main(String[] args)throws Exception {
		MyRunnable runnable=new MyRunnable();
		Thread thread=new Thread(runnable);
		thread.start();
	}
}

PS:线程的启动是start()方法,不是run()方法。继承Thread类的方式是有局限性的,因为java是单继承,为了改变这个局限性,我们可以实现Runnable接口来实现多线程


二、  currentThread()方法

currentThread()方法可以返回代码段正在被哪个线程调用的信息。
package com.ztz.myThread;

public class MyThread{
	public static void main(String[] args)throws Exception {
		System.out.println(Thread.currentThread().getName());
	}
}
运行该方法,控制台输出:
main

说明:main方法被名为main线程调用。Thread.currentThread().getName()是获得线程名

package com.ztz.myThread;

public class MyThread extends Thread{
	public MyThread() {
		System.out.println("构造方法:"+Thread.currentThread().getName());
	}
	@Override
	public void run() {
		System.out.println("run:"+Thread.currentThread().getName());
	}
	public static void main(String[] args)throws Exception {
		MyThread thread=new MyThread();
		thread.start();
	}
}
运行该方法控制台输出:
构造方法:main
run:Thread-0


其实,main也就是主线程了Thread-0是子线程,如果在启动个线程就是Thread-1了。


三、  sleep()方法

方法sleep()的作用是在指定的毫秒数内让当前正在执行的线程休眠(暂停执行),这个正在执行的线程是指this.currentThread()返回的线程。
package com.ztz.myThread;

public class MyThread extends Thread{
	@Override
	public void run() {
		try{
			System.out.println("run start:"+System.currentTimeMillis());
			Thread.sleep(2000);
			System.out.println("run end:"+System.currentTimeMillis());
		}catch(Exception e){
			
		}
	}
	public static void main(String[] args)throws Exception {
		MyThread thread=new MyThread();
		System.out.println("thread start:"+System.currentTimeMillis());
		thread.start();
		System.out.println("thread end:"+System.currentTimeMillis());
	}
}

输出结果:
thread start:1437233204468
thread end:1437233204468
run start:1437233204468
run end:1437233206468

四、  getId()方法

getId()方法的作用是取得线程的唯一标识。
package com.ztz.myThread;

public class MyThread{
	public static void main(String[] args)throws Exception {
		Thread currentThread = Thread.currentThread();
		System.out.println(currentThread.getName()+"--->"+currentThread.getId());
	}
}

输出结果:
main--->1



版权声明:本文为博主原创文章,未经博主允许不得转载。

转载于:https://my.oschina.net/u/1246822/blog/527710

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值