Java 线程的创建

一个Java程序实际上是一个JVM进程

JVM用一个主线程来执行main()方法

在main()方法中有可以启动多个线程

那么怎么去创建一个线程呢?

第一种,继承Thread类

public class MyThread extends Thread {
@Override
public void run() {
System.out.println();
}
}
public class MyThreadTest {
public static void main(String[] args) {
Thread t = new MyThread();
t.start();
}
}
步骤:
  1. 继承Thread
  2. 覆写run()方法
  3. 创建MyThread实例
  4. 调用start()方法启动线程

第二种,实现Runnable接口

  public class MyThread implements Runnable {

    @Override
public void run() {
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
Runnable runnable = new MyThread();
Thread thread = new Thread(runnable);
thread.start();
}
}
步骤:
  1. 实现Runnable接口
  2. 覆写run()方法
  3. 在main()方法中创建Runnable实例
  4. 创建Thread实例并传入Runnable
  5. 调用start()方法启动线程

public class Main {

public static class MyThread extends Thread {
private String name;

public MyThread(String name) {
this.name = name;
}

@Override
public void run() {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(200L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Hello," + name);
}
}
}

public static void main(String[] args) {
System.out.println("main thread start ......");
Thread t1 = new MyThread("lao wang");
t1.start();
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(200L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Hello, lao liu" );
}
System.out.println("main thread end ......");
}
}
这段代码输出什么?
从上得出线程的执行顺序是不确定的,
这里还要提一个概念 线程的优先级,可以通过Thread.setPriority(int n)设置优先级,默认5,范围:1-10,但是设置优先级并不能保证线程的执行顺序,只能说被操作系统调度的可能性高。

总结

  1. Java用Thread对象表示一个线程,通过调用start()方法来启动线程

  2. 一个线程对象只能调用一次start()方法

  3. 线程的执行代码是run() 方法

  4. 线程的调度是由操作系统决定的,线程本身无法决定

  5 Thread.sleep()可以把线程暂停一段时间

原文地址:https://www.cnblogs.com/wangpenglen/p/11555692.html