java多线程2(线程的创建方式以及启动)

本文介绍了Java中创建线程的三种方式:继承Thread类、实现Runnable接口和实现Callable接口。并通过实例展示了如何启动线程及获取Callable线程的返回值。

上一篇文章中我们学习了任务,线程的概念以及任务和线程的关系,下面看看创建线程的方式有哪些

一、线程创建方式

Thread类的继承、Runnable接口的实现、Callable<T>接口的实现(Callable接口有返回值)

平时大家使用多的可能就是Thread类的继承和Runnable接口的实现这两种,下面我们来看看实例

1、继承Thread类创建线程

package test3;

public class ExtendThread extends Thread {
	@Override
	public void run(){
		System.out.println("线程创建,任务执行 Thread!");
	}
}

2、实现Runnable接口

package test3;

public class ImplRunnable  implements Runnable{
	@Override
	public void run() {
		System.out.println("线程创建,任务执行 Runnable!");
	}
}

我们先来看看这两种大家常用的两种方式,其实你看源码你会发现Thread 类是Runnable接口的实现类:

public
class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }

    private char        name[];
    private int         priority;
    private Thread      threadQ;
    private long        eetop;
看到了吧其实Thread类是实现了Runnable接口,所以为了任务和线程的执行的分开以及避免java单继承我们应该多用Runnable 而少用Thread。

按照java规范定义了任务

3、创建线程、启动线程

package test3;

public class MainTest {
public static void main(String[] args) {
	//创建线程,并将任务附着在线程上
	ExtendThread  thread1= new ExtendThread();
	//定义任务
	ImplRunnable  runnable= new ImplRunnable();
	//声明线程并将任务附着到线程上
	Thread thread= new Thread(runnable);
	//启动线程
	thread1.start();
	//启动线程
	thread.start();
}
}

调用start()方法具体干了什么在前一篇文章中我们学习了,这里就简单说说,当调用start()方法时启动了当前线程并且jvm调用了这个线程中的run()方法,所以调用start()方法时是两个线程在运行。jvm就调用了我们在线程中定义的run方法来驱动执行我们的任务。

其实我们可以直接调用run()方法来执行我们任务,但我们为什么不调用run()方法来直接执行任务那,那样的话我们就实现不了多线程而是在"main"这个线程中顺序的去执行了我们定义的任务即run()方法,而不会jvm调用执行。


4、执行结果


看到没调用start()方法是多个线程竞争执行,所以有可能后面启动的线程先获取cpu资源先执行完任务结束线程!


5、有返回值的线程创建 Callable接口实现

package test3;

import java.util.concurrent.Callable;
public class ImplCallable implements Callable<String> {
	@Override
	public String call() throws Exception {
		System.out.println("线程创建,任务执行 Callable!");
		String res= "callable 返回值";
		//休眠一秒钟
		Thread.sleep(1000);
		return res;
	}
}


6、启动有返回值线程并获取返回值


package test3;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class MainTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
	//创建线程,并将任务附着在线程上
	//ExtendThread  thread1= new ExtendThread();
	//定义任务
	//ImplRunnable  runnable= new ImplRunnable();
	//声明线程并将任务附着到线程上
	//Thread thread= new Thread(runnable);
	//启动线程
	//thread1.start();
	//启动线程
	//thread.start();
	ImplCallable  call= new ImplCallable();
	FutureTask task= new FutureTask(call);
	//任务附着到线程并启动线程
	new Thread(task).start();
	System.out.println(System.currentTimeMillis());
	//如果任务还没执行完则线程阻塞等待获取返回值
	System.out.println(task.get());
	System.out.println(System.currentTimeMillis());
}
}

启动线程并执行任务,如果任务没有执行完则调用get()方法会阻塞其他线程,直到获取返回值,下面是上面程序执行的结果:



因为在任务类call()方法中我们休眠了一分钟,所以在task.get()时一直在等待获取结果,直到获取结果才执行下面的。

这里对Future、FutureTask以及线程池等不会进行学习,在之后的文章中我们再学习。


7、多个线程抢占式执行

package test3;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class MainTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
	ExtendThread  thread1= new ExtendThread();
	ImplRunnable  runnable= new ImplRunnable();
	Thread thread2= new Thread(runnable);
	ImplCallable  call= new ImplCallable();
	FutureTask task= new FutureTask(call);
	Thread thread3= new Thread(task);
	//启动线程
	thread1.start();
	thread2.start();
	thread3.start();
}
}
三个线程启动一次是按照Thread、Runnable和Callable<T>来启动的,下面看看执行结果

线程创建,任务执行 Thread!
线程创建,任务执行 Callable!
线程创建,任务执行 Runnable!
从中我们能看到,执行的结果不是按照启动的顺序来的,因为这就是多线程(jvm现在大多是抢占式的),谁抢到了cpu执行权限谁就执行,所以有这样的结果是正确的。


8、多线程顺序执行

package test3;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class MainTest {
public static void main(String[] args) throws InterruptedException, ExecutionException {
	ExtendThread  thread1= new ExtendThread();
	ImplRunnable  runnable= new ImplRunnable();
	Thread thread2= new Thread(runnable);
	ImplCallable  call= new ImplCallable();
	FutureTask task= new FutureTask(call);
	Thread thread3= new Thread(task);
	//启动线程
	thread1.start();
	thread1.join();//在thread1线程没有执行完之前其他线程都阻塞
	thread2.start();
	thread2.join();////在thread2线程没有执行完之前其他线程都阻塞
	thread3.start();
}
}

执行结果:

线程创建,任务执行 Thread!
线程创建,任务执行 Runnable!
线程创建,任务执行 Callable!

总结:

上面我们看到了有三种方式来创建线程,而Thread就是实现了Runnable接口所以建议多使用Runnable而少用Thread类。如果需要有返回值的线程则可以使用Callable<T>来实现。

上面我们启动多个线程后不是顺序执行,因为现在我们使用的很多jvm都是抢占式的,所以即使是我们第一个开启的线程不一定能第一个获取cpu的执行权限,就好比大家挤地铁即使你站在前面但你不一定能较早挤进地铁。所以说线程的执行顺序是随机的。

顺序的执行线程,join方法其实使用到了线程通信,线程通信以及线程join()方法之后会详细学习。

我们发现多个线程的执行不是顺序执行,但通过一定的手段能让他顺序执行,下一篇我们先来看看线程的启动、执行、阻塞和结束即线程的生命周期这样就能明白这里的非顺序执行和顺序执行的原因!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值