线程Thread,Runnable
package com.aaa; //public class Ticket extends Thread{ //1.当主线程发现这个类的对象继承了Thread后,就会开一个新的线程让其执行 public class Ticket implements Runnable{ //1.实现runnable public void run(){//2.重写该方法 for(int i = 1;i < 50000 ;i++){ try { Thread.sleep(100);//哪个线程运行这个方法,那个线程就会sleep掉,醒来后并不是马上执行,而是 //等到CPU执行到自己,所以sleep时间可能会超过这个时间 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Thread.yield();//哪个线程运行这个方法时,就会暗示CPU自己已经运行完成了,可以将时间片交给其它的线程 System.out.println(Thread.currentThread().getName()+" "+i); } } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub //得到主线程: System.out.println(Thread.currentThread().getName()); // Ticket t1 = new Ticket(); //继承Thread的写法 // Ticket t2 = new Ticket(); Thread t1 = new Thread(new Ticket()); //实现runnable接口的写法 Thread t2 = new Thread(new Ticket()); t1.setDaemon(true); t2.setDaemon(true);//设置t1,t2为后台线程,垃圾回收也是后台线程 t1.setPriority(1);//最高级别 //默认是5 t2.setPriority(10);//最低级别 //如果你期望某一个线程运行的更快些,或者更快完成,可以设置优先级更高一些,就可能得到更多的CPU运行时间(并不绝对) t1.start();//3.用start()来调用run方法 t2.start(); for(int i = 0 ;i<100 ;i++){ try { System.out.println("主线程"+i); Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("------------------------------------------------全部完成---------------"); //主线程的代码运行完成之后我们发现t1,t2继续运行,主线程将继续等待t1,t2完成,因为t1,t2是前台线程 //当t1,t2设置为后台线程后,主线程代码一旦完成,就会停止一切后台线程的运行 } }