创建线程的方法
1.继承Thread类来创建线程,这个方法的好处是this代表的就是当前线程,不需要通过Thread.currentThread()来获取当前线程的引用。
public class main {
public static class myThread extends Thread{
@Override
public void run() {
System.out.println("创建出来的线程");
}
}
public static void main(String[] args) {
myThread t1=new myThread();
t1.start();
}
}
2.实现Runnable接口,并且调用Thread的构造方法时将Runnable对象作为target参数传入来创建线程对象,好处是可以规避类的单继承限制,但需要通过Thread.currentThread()来获取当前线程的引用。
public class main {
public static class MyRunnbale implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"通过Runnable创建出来的线程");
}
}
public static void main(String[] args) {
Thread t1=new Thread(new MyRunnbale());
t1.start();
}
}
Thread.currentThread()可以获取当前线程的引用。
使用匿名类创建Thread对象
使用匿名类创建Runnable子类对象
使用Lambda表达式创建Runnable子类对象
Thread的常见属性
public class ThreadFields {
public static void main(String[] args) {
//Thread.currentThread()
//获取当前线程Thread对象
Thread currentThread=Thread.currentThread();
System.out.println(currentThread.getName());//获取名称
System.out.println(currentThread.getId());//获取Id
System.out.println(currentThread.getPriority());//优先级
System.out.println(currentThread.getState());//状态
System.out.println(currentThread.isDaemon());//是否是后台线程
System.out.println(currentThread.isAlive());//是否存活
System.out.println(currentThread.isInterrupted());//是否被中断
}
}
/*
执行结果:
main
1
5
RUNNABLE
false
true
false
*/
Thread的常见构造方法
public class main {
public static class myThread extends Thread{
@Override
public void run() {
}
}
public static class MyRunnable implements Runnable{
@Override
public void run() {
}
}
public static void main(String[] args) {
myThread t1=new myThread();
Thread t2=new Thread(new MyRunnable());
Thread t3=new Thread("这是我的名字");
Thread t4=new Thread(new MyRunnable(),"这是MyRunnable()创建出来的线程");
t1.start();t2.start();t3.start();t4.start();
}
}