120. 多线程有问题的点

Runnable 线程创建

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable()
Thread thread = new Thread(myRunnable);
thread.start(); // 启动新线程
}
}

class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("start new thread!");
}
}

2

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable()
new Thread(myRunnable).start(); // 启动新线程
}
}

class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("start new thread!");
}
}

3

1
2
3
4
Thread t = new Thread(() -> {
System.out.println("start new thread!");
});
t.start(); // 启动新线程

4

1
2
3
new Thread(()-> {
System.out.println("start new thread!");
}).start();

Note

要想给每个实例不一样的参数:用构造函数

Thread 创建线程

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Main {
public static void main(String[] args) {
Thread t = new MyThread();
t.start(); // 启动新线程
}
}

class MyThread extends Thread {
@Override
public void run() {
System.out.println("start new thread!");
}
}