1、实现Runnable接口
1 package test; 2 3 4 5 public class ThreadTest implements Runnable{ 6 public void tt(){ 7 Thread t = new Thread(this); 8 t.start(); 9 } 10 11 @Override 12 public void run() { 13 while(true){ 14 } 15 } 16 public static void main(String[] args) { 17 ThreadTest t = new ThreadTest(); 18 Thread t2 = new Thread(new Runnable() { 19 @Override 20 public void run() { 21 } 22 }); 23 t2.start(); 24 t.tt(); 25 } 26 }
2、继承Thread类
1 package test; 2 3 public class test1 extends Thread{ 4 public void tt(){ 5 this.start(); 6 } 7 @Override 8 public void run() { 9 System.out.println("sfsdfdsf"); 10 } 11 public static void main(String[] args) { 12 test1 t= new test1(); 13 t.tt(); 14 } 15 }
3、内包格式
1 Thread t2 = new Thread(new Runnable() { 2 @Override 3 public void run() { 4 // TODO Auto-generated method stub 5 6 } 7 }); 8 t2.start();
获取虚拟机中的所有线程
1 Map<Thread, StackTraceElement[]> maps=Thread.getAllStackTraces(); 2 for(Thread t:maps.keySet()){ 3 System.out.println(t.getName());//线程名 4 System.out.println(t.isAlive());//是否还在执行 5 6 }
原文:http://www.cnblogs.com/jj-0611/p/6629352.html