这一章节我们来简单回顾一下多线程的创建,其实这个在之前的从头认识java的系列文章里面已经聊到过这个话题,在这里重新梳理一遍,当成这个系列的开篇。
1.继承Thread
Thread的构造器
Thread()
Allocates a new
Thread object.
|
Thread(Runnable target)
Allocates a new
Thread object.
|
Thread(Runnable target, String name)
Allocates a new
Thread object.
|
Thread(String name)
Allocates a new
Thread object.
|
Thread(ThreadGroup group, Runnable target)
Allocates a new
Thread object.
|
Thread(ThreadGroup group, Runnable target, String name)
Allocates a new
Thread object so that it has
target as its run object, has the specified
name as its name, and belongs to the thread group referred to by
group .
|
Thread(ThreadGroup group, Runnable target, String name, long stackSize)
Allocates a new
Thread object so that it has
target as its run object, has the specified
name as its name, and belongs to the thread group referred to by
group , and has the specified
stack size.
|
Thread(ThreadGroup group, String name)
Allocates a new
Thread object.
|
(1)使用默认的构造器
package com.ray.deepintothread.ch01.topic_1;
public class SimpleExtendThread {
public static void main(String[] args) {
ThreadOne threadOne = new ThreadOne();
Thread thread = new Thread(threadOne);
System.out.println("start");
thread.start();
}
}
class ThreadOne extends Thread {
@Override
public void run() {
System.out.println("begin to run");
super.run();
System.out.println("end to run");
}
}
输出:
start
begin to run
end to run
(2)使用带名字的构造器
package com.ray.deepintothread.ch01.topic_1;
public class SimpleExtendThread2 {
public static void main(String[] args) {
ThreadOne2 threadOne = new ThreadOne2("线程A");
Thread thread = new Thread(threadOne);
System.out.println("start");
thread.start();
}
}
class ThreadOne2 extends Thread {
private String name;
public ThreadOne2(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("Thread " + name + " begin to run");
super.run();
System.out.println("Thread " + name + " end to run");
}
}
start
Thread 线程A begin to run
Thread 线程A end to run
2.实现Runnable
package com.ray.deepintothread.ch01.topic_1;
public class SimpleRunnableImpl {
public static void main(String[] args) {
RunnableOne threadOne = new RunnableOne();
Thread thread = new Thread(threadOne);
System.out.println("start");
thread.start();
}
}
class RunnableOne implements Runnable {
@Override
public void run() {
System.out.println("begin to run");
}
}
输出:
start
begin to run
由于java是单根继承,因此,我们更多的时候会使用实现Runnable的方式来实现多线程。
总结:这一章节简单的回顾一下多线程的创建。
我的github:https://github.com/raylee2015/DeepIntoThread