标签:
1.目的
创建线程,即拿到一个线程实例。这个线程实例必须具备开启、等待、唤醒等控制自身生命周期的方法。
2.创建Thread线程
方式一:new Thread()、new Thread(String name)
1 /** 2 *两个构造器也有区别:线程名不同 3 */ 4 public class Thread implements Runnable { 5 private char name[]; 6 7 //1.不带参 8 /* 9 *Automatically generated names are of the form *"Thread-"+n, where n is an integer 10 */ 11 public Thread() { 12 init(null, null, "Thread-" + nextThreadNum(), 0); 13 } 14 private static synchronized int nextThreadNum() { 15 return threadInitNumber++; 16 } 17 //2.带参 18 public Thread(String name) { 19 init(null, null, name, 0); 20 } 21 //初始化线程—init()? 22 private void init(ThreadGroup g, Runnable target, String name,long stackSize) { 23 init(g, target, name, stackSize, null); 24 } 25 private void init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc) { 26 if (name == null) { 27 throw new NullPointerException("name cannot be null"); 28 } 29 this.name = name.toCharArray(); 30 /**后面是初始化线程代码—略*/ 31 } 32 }
方式二:new Thread(Runnable run)
public interface Runnable {
public abstract void run();
}
/* *用“外置Runnable对象”覆盖、取代当前对象(目的是让注入对象也能拥有Thread对象的管理线程的方法) */ public class Thread implements Runnable { public void run() { if (target != null) { target.run(); //运行“外置线程对象” } //至于其它方法,针对的对象都是Thread.currentThread() }
3.创建自定义线程
方式一:继承java.lang.Thread
/**
*1.构造类
*/
public class MyThread extends Thread { //@Override //是否覆盖父类对象的run()方法 public void run() { //do something } } /**
*2.创建实例
*/ public class Main{ public void static void main(String args){ Thread t =new MyThread();
t.run(); //t的run()被调用;t的线程启动
} }
方法二:实现Runnable接口
public class MyThread implements Runnable { public run() { //do something }
/**
*2.创建实例
*/
public class Main{
public void static void main(String args){
MyThread mt =new MyThread();
Thread t =new Thread(mt); //创建Thread线程——>方式二
t.run(); //t的run()被调用;mt的线程启动,t的线程未启动
}
}
标签:
原文地址:http://www.cnblogs.com/crazyYouth/p/5406169.html