每当用 java 命令解释一个程序类时,操作系统就会启动一个进程,而 main 只是这新进程上的一个子线程。
JVM 启动的时候会执行 main 线程和 gc 线程。
线程的命名与取得:取得的是执行当前本方法的线程名。
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
MyThread myThread2 = new MyThread();
new Thread(myThread1).start();
new Thread(myThread2,"Thread A").start();
myThread1.run();
}
}
默认情况下,在休眠的时候如果设置了多个线程对象,那么所有的线程对象将一起进入 run 方法(先后顺序实在是太短了)。
class MyThread implements Runnable{
@Override
public void run() {
for(int i = 0; i < 10; i ++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
new Thread(myThread1,"Thread A").start();
new Thread(myThread1,"Thread B").start();
new Thread(myThread1,"Thread C").start();
new Thread(myThread1,"Thread D").start();
}
}
优先级越高的线程对象越有可能先执行
主线程的优先级别是中等。
class MyThread implements Runnable{
@Override
public void run() {
for(int i = 0; i < 10; i ++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread1 = new MyThread();
Thread A = new Thread(myThread1,"Thread A");
Thread B = new Thread(myThread1,"Thread B");
Thread C = new Thread(myThread1,"Thread C");
Thread D = new Thread(myThread1,"Thread D");
A.setPriority(Thread.MAX_PRIORITY); //10
B.setPriority(Thread.MIN_PRIORITY); //1
C.setPriority(Thread.NORM_PRIORITY); //5
D.setPriority(Thread.MIN_PRIORITY); //1
A.start();
B.start();
C.start();
D.start();
System.out.println(Thread.currentThread().getName() + " " + Thread.currentThread().getPriority());
}
}