
public class FirstTreading{
public static void main(String[] args) {
MyTread myTread = new MyTread();
myTread.start();
}
}
class MyTread extends Thread{
public void run(){
System.out.println("继承Thread类方法");
}
}
Thread 类本质上是实现了 Runnable 接口的一个实例,代表一个线程的实例。 启动线程的唯一方法就是通过 Thread 类的 start()实例方法。 start()方法是一个 native 方法,它将启动一个新线程,后执行 run()方法。
1.2实现Runnable接口public class SecondThreading {
public static void main(String[] args) {
MyTread2 myTread2 = new MyTread2();
Thread thread = new Thread(myTread2);
thread.start();
}
}
class MyTread2 implements Runnable {
@Override
public void run() {
System.out.println("第二种方法:实现Runnable");
}
}
当传入一个Runnable target 参数给Thread后会调用target.run()
@Override
public void run() {
if (target != null) {
target.run();
}
}
Thread的Start源码
public synchronized void start() {
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
}
}
}
1.3实现Callable接口通过FutureTask包装的方式
public class ThirdTreading {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// TODO Auto-generated method stub
//创建Callable实现类的实现
Callable
1.4通过线程池创建线程
public class FourthThreading{
private static int POOL_NUM = 10; //线程池数量
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
ExecutorService executorService1 = Executors.newFixedThreadPool(5);
for(int i = 0; i欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)