java创建线程的2种方式

 线程:就是程序的执行线索。

 线程安全:同一段代码用多线程,程序运行的结果与非多线程一样,就是线程安全的。

//1第一种是new Thread的子类(重写run方法)

public static void main(String[] args) {
Thread thread1 = new Thread(){
public void run() {
while(true){
try {
Thread.sleep(100);
System.out.println("1:"+Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}};

thread1.start();

//2第二种是new Runnable()
Thread thread2 = new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(100);
System.out.println("2:"+Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});

thread2.start();

原文地址:https://www.cnblogs.com/dsking/p/5253280.html