方法一 : 继承Thread对run重写
1.MyThread 继承了Thread 然后对run进行重写
class MyThread extends Thread{
@Override
public void run() {
while (true){
System.out.println("hello world!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2.对MyThread进行实例化,调用start()启动线程!
public class ThreadDemo1 {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
myThread.start();
while (true){
System.out.println("main!");
Thread.sleep(1000);
}
}
}
方法二 : 实现Runnable接口,重写run
1.实现Runnable接口,重写run,其中Runnable仅代表一段代码,具体线程还是需要搭配Thread类,其的好处是降低了代码的耦合性!
class MyThread1 implements Runnable {
@Override
public void run() {
while (true){
System.out.println("hello");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2.创建 Thread 类实例, 调⽤ Thread 的构造⽅法时将 Runnable 对象作为 target 参数,调用start()启动线程!
public class ThreadDemo2 {
public static void main(String[] args) throws InterruptedException {
Runnable runnable = new MyThread1();
Thread thread = new Thread(runnable);
thread.start();
while (true){
System.out.println("mian");
Thread.sleep(1000);
}
}
}
方法三 : 继承Thread对run重写(使用匿名内部类)
写{}是定义一个类,与此同时并继承自Thread,在此次定义子类的属性与方法,主要目的在于重写run
public class ThreadDemo3 {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(){
@Override
public void run() {
while (true){
System.out.println("hello!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();
while (true){
System.out.println("main");
Thread.sleep(1000);
}
}
}
方法四 : 实现Runnable接口,重写run(使用匿名内部类)
Thread构造方法的参数,填写了Runnable的匿名内部类的实例
public class ThreadDemo4 {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new Runnable(){
@Override
public void run() {
while(true){
System.out.println("hello");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
while (true){
System.out.println("mian");
Thread.sleep(1000);
}
}
}
方法五 : [常用/推荐]使用lambda表达式
lambda 表达式创建 Runnable ⼦类对象(lambda代替了Runnable的位置)
public class ThreadDemo5 {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
while (true){
System.out.println("hello!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
while (true){
System.out.println("main");
Thread.sleep(1000);
}
}
}