
在线程中有一个常见的类,可以帮助我们对线程进行创建,除此之外还有一些其他的使用比如线程的调用、转让、打断都有所涉及。这里我们先简单讲一下Thread类的作用,然后展示它的使用方法,最后就其中的currentThread()方法带来实例的展示,带领大家初步体验Thread类的作用。
1.Thread类说明
实现了Runnable接口。
启动线程的实例:
1 2 | MyThread my = new MyThread();
my.start();
|
2.Thread类相关方法
1 2 3 4 5 6 7 8 | public static Thread.yield()
public static Thread.sleep()
public join()
public interrupte()
|
3.currentThread()方法实例
currentThread()方法可以返回代码被那个线程调用的信息。
测试方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public class MyThread extends Thread{
public MyThread(){
super ();
}
public MyThread(String name){
super ();
this .setName(name);
System.out.println( "构造器中线程名字:" + Thread.currentThread().getName());
}
@Override
public void run() {
super .run();
System.out.println( "this is MyThread" );
System.out.println( "run方法中线程名字:" + Thread.currentThread().getName());
}
public static void main(String[] args){
MyThread myThread = new MyThread( "myThread-name" );
myThread.start();
}
}
|
输出内容:
1 2 3 | 构造器中线程名字:main
this is MyThread
run方法中线程名字:myThread-name
|
以上就是thread类在java线程中的使用,本篇对thread类做了一个大致的使用介绍,关于它的用法还有很多种,我们会在后期文章中不断更新,小伙伴们可以关注这方面的内容。