1、线程的创建
一、方式一:继承Thread类
1、继承Thread类
public MyThread extend Thread{
int i = 0;
2、重写run()
public void run(){
while(true){
if(i <= 100){
System.out.println(i);
}
else{
break;
}
}
}
}
3、创建Thread类的子类的对象
Mythread t1 = new Mythread();
4、调用start()方法来启动线程
t1.start();
二、实现Runnable接口
//1.实现Runnable接口 class MyRunnable implements Runnable{ int i = 0; //2.重写run()方法 @Override public void run() { while(true){ if(i<=100) { System.out.println(Thread.currentThread().getName() + "---" + i); i++; } else { break; } } } } //3.创建Runnable接口实现类的对象 MyRunnable myRunnable = new MyRunnable(); //4.创建Thread类的对象,并调用有参构造器传入Runnable实现类的对象
Thread thread = new Thread(myRunnable); //5.调用start()启动线程 thread.start();
1、实现Runnable时,调用Thread的start()方法为什么会调用Runnable接口实现类的run()方法?
因为我们在创建Thread类的对象时,调用有参构造器传入了Runnable接口实现类的对象,在源码中是这样写着:
//1、源码中传入Runnable接口实现类对象的构造器,传入target对象 public Thread(Runnable target) { this(null, target, "Thread-" + nextThreadNum(), 0); } //2、调用start()方法时,会调用start0() public synchronized void start() { /** * This method is not invoked for the main method thread or "system" * group threads created/set up by the VM. Any new functionality added * to this method in the future may have to also be added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0) throw new IllegalThreadStateException(); /* Notify the group that this thread is about to be started * so that it can be added to the group's list of threads * and the group's unstarted count can be decremented. */ group.add(this); boolean started = false; try { start0(); //3、而start0()方法会调用target的run(),也就是传入Runnable接口实现类对象的run()方法 private native void start0(); /** * If this thread was constructed using a separate * {@code Runnable} run object, then that * {@code Runnable} object's {@code run} method is called; * otherwise, this method does nothing and returns. * <p> * Subclasses of {@code Thread} should override this method. * * @see #start() * @see #stop() * @see #Thread(ThreadGroup, Runnable, String) */ @Override public void run() { if (target != null) { target.run(); } }
三、调用start():
1、调用start()会启动线程
2、调用start()会调用run()
3、同一个线程的start()方法只能调用一次,因为在底层代码中是这样写着:
1 2 3 public synchronized void start() { 4 /** 5 * This method is not invoked for the main method thread or "system" 6 * group threads created/set up by the VM. Any new functionality added 7 * to this method in the future may have to also be added to the VM. 8 * 9 * A zero status value corresponds to state "NEW". 10 */ 11 if (threadStatus != 0) 12 throw new IllegalThreadStateException();
在执行start()方法时,首先会判断“threadStatus”是否为0,如果为0,则可以调用start(),否则会报错。
四、在main()中,直接调用run()不会启动线程,run()方法直接在main()主线程中进行调用
五、继承Thread类与实现Runnable接口的比较:
1、实现Runnable接口没有类单继承的局限性。
2、实现Runnable接口可以更适合处理多个线程共享数据
浙公网安备 33010602011771号