Java线程总结(一)
2017-12-24 12:31
197 查看
首先,先贴上一个简单的线程实例:
运行结果如下:
由运行结果可以看出,程序中有两个线程,一个是主线程,另一个是我手动创建的线程,主线程都是jvm创建的。
线程执行start()方法不代表线程的启动顺序,如下例:
运行结果如下,执行顺序与调用start()方法的顺序不一致:
public class MyThread extends Thread{ @Override public void run(){ try { for (int i = 0; i < 10; i++){ int time = 1000; Thread.sleep(time); System.out.println("run = " + Thread.currentThread().getName()); } }catch (InterruptedException e){ e.printStackTrace(); } } public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.setName("MyThread"); myThread.start(); try{ for (int i = 0; i < 10; i++){ int time = 1000; Thread.sleep(time); System.out.println("main = " + Thread.currentThread().getName()); } }catch (InterruptedException e){ e.printStackTrace(); } } }
运行结果如下:
由运行结果可以看出,程序中有两个线程,一个是主线程,另一个是我手动创建的线程,主线程都是jvm创建的。
线程执行start()方法不代表线程的启动顺序,如下例:
public class MyThread extends Thread{ private int i; public MyThread(int i){ super(); this.i = i; } @Override public void run(){ System.out.println(i); } public static void main(String[] args) { MyThread thread1 = new MyThread(1); MyThread thread2 = new MyThread(2); MyThread thread3 = new MyThread(3); MyThread thread4 = new MyThread(4); MyThread thread5 = new MyThread(5); MyThread thread6 = new MyThread(6); MyThread thread7 = new MyThread(7); MyThread thread8 = new MyThread(8); MyThread thread9 = new MyThread(9); MyThread thread10 = new MyThread(10); thread1.start(); thread2.start(); thread3.start(); thread4.start(); thread5.start(); thread6.start(); thread7.start(); thread8.start(); thread9.start(); thread10.start(); } }
运行结果如下,执行顺序与调用start()方法的顺序不一致:
相关文章推荐
- Java线程安全总结
- java线程安全总结
- java线程安全总结
- java多线程学习总结之二:线程状态的转换
- java线程总结--synchronized关键字,原理以及相关的锁
- Java线程总结(六):并发包------线程同步Lock
- Java线程学习记录与总结
- Java中线程用法总结
- Java多线程总结(一):多线程简介及线程的创建
- java线程总结(3/5)
- Java多线程总结之线程安全队列Queue
- java线程总结1--线程的一些概念基础以及线程状态
- 新手-JAVA-线程-总结
- java线程安全总结(一)
- Java线程总结
- java线程安全总结
- Java中守护线程的总结
- Java线程相关知识总结
- Java中的线程Thread总结
- Java中守护线程的总结