一:java创建线程的五种方法
1.创建线程的第一种方法,使用Thread来实现
class MyThread extends Thread {
@Override
public void run() {
while(true){
System.out.println("Hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public class test {
public static void main(String[] args) {
Thread t = new MyThread();
t.start();
while(true){
System.out.println("Hello main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
2.创建线程的第二种方法,使用Runnable接口来实现
class MyRunnable implements Runnable{
@Override
public void run() {
while(true){
System.out.println("Hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public class test2 {
public static void main(String[] args) {
Thread t=new Thread(new MyRunnable());
t.start();
while(true){
System.out.println("Hello main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
3.创建线程的第三种方法(匿名内部类)
public class test3 {
public static void main(String[] args) {
Thread t = new Thread() {
@Override
public void run() {
while (true) {
System.out.println("Thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
};
t.start();
while (true) {
System.out.println("main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
4.匿名内部类,针对Runnable
public class test4 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println("thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
});
t.start();
while (true) {
System.out.println("main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
创建Runnable的实例,来重写他的run方法。
5.使用lambda表达式来代替重写的run方法
public class test5 {
public static void main(String[] args) {
Thread t=new Thread(()->{
while(true){
System.out.println("thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
t.start();
while(true){
System.out.println("main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
总结:
1.关于线程各种属性的设置,一定要放在线程start之前.
2.多线程的优势可以增加程序运行的速度
-
ID 是线程的唯⼀标识,不同线程不会重复
-
优先级高的线程理论上来说更容易被调度到
-
关于后台线程,需要记住⼀点:JVM会在⼀个进程的所有非后台线程结束后,才会结束运行
-
是否存活,即简单的理解,为 run 方法是否运行结束了
获取当前线程引用:
public class ThreadDemo {
public static void main(String[] args) {
Thread thread = Thread.currentThread();
System.out.println(thread.getName());
}
}
即返回当前线程对象的引用