一.继承Thread ,重写run
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 Demo1 {
public static void main(String[] args) throws InterruptedException {
Thread t = new MyThread();
t.start();//执行run方法中的逻辑
while(true) {
System.out.println("hello main");
Thread.sleep(1000);
}
}
}
运行结果:
每秒中输出一次可能是main开头,也可能是thread开头,说明多个线程的调度顺序是"无序的",在操作系统内部也称为"抢占执行".
二.实现Runable,重写run,把Runable实例传入Thread中
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public class Demo2 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new MyRunnable());
t.start();
while (true) {
System.out.println("hello main");
Thread.sleep(1000);
}
}
}
三.针对一的变形,使用匿名内部内,继承Thread 并重写run.
public class Demo3 {
public static void main(String[] args) {
new Thread() {
@Override
public void run() {
while (true) {
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}.start();
//t.start();
while (true) {
System.out.println("hello main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
1.创建一个子类(没有名字).
2.同时也创建了这个子类的实例 .
3.重写run方法.
四.匿名内部类,针对Runnable
public class Demo4 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {//此处匿名内部类,只针对Runnable和Thread没有关系,只是把Runnable作为参数传入到Thread的构造方法中
@Override
public void run() {
while(true) {
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
});
t.start();
while (true) {
System.out.println("hello main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
1.创建新的类,实现Runnable,名字是匿名的
2.创建了这个类的实例(一次性的)
3.重写run方法.
五.使用lambda 表达式
public class Demo5 {
public static void main(String[] args) {
Thread t = new Thread(() -> {
while (true) {
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
t.start();
while (true) {
System.out.println("hello main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}