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();
线程安全:同一段代码用多线程,程序运行的结果与非多线程一样,就是线程安全的。
//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();
相关文章推荐
- eclipse 重source folder,package,folder的区别
- 自己编译JDK
- Java多线程
- RxJava 多线程控制
- java 遍历map 方法 集合 五种的方法
- JAVA CAS实现原理与使用
- 【leetcode】【171】Excel Sheet Column Number
- spring 后置处理器BeanFactoryPostProcessor和BeanPostProcessor的用法和区别
- 【转】Win CE 平台上java虚拟机CrE-ME的安装
- 安装java之后,找不到tools.jar 和dt.jar
- springmvc整合Mybatis的Log4j日志输出问题
- 【leetcode】【169】Majority Element
- 简述Java异步上传文件的三种方式
- Spring Boot 填坑日志
- Struts内置类型转换器
- Leetcode:102. Binary Tree Level Order Traversal(JAVA)
- Eclipse报错:java.lang.ClassNotFoundException: ContextLoaderListener(转载的)
- 【leetcode】【168】Excel Sheet Column Title
- java 遍历arrayList的四种方法
- JAVA多线程下载的实现