您的位置:首页 > 编程语言 > Java开发

java创建线程的2种方式

2016-03-08 11:14 501 查看
线程:就是程序的执行线索。

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

//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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: