继承Thread方式
一、继承Thread类
创建线程比较原始的一种方式,现在已经不推荐了。
package week3.demo;
public class ThreadByExtend extends Thread{
public static volatile int count = 0;
//Thread真正执行的代码段
public void run() {
for(int i=0;i<50;i++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "sold "+(i+1)+" tickets total Sold:" + (++count));
}
}
public static void main(String[] argv) throws InterruptedException{
ThreadByExtend myThread1 = new ThreadByExtend();
ThreadByExtend myThread2 = new ThreadByExtend();
ThreadByExtend myThread3 = new ThreadByExtend();
ThreadByExtend myThread4 = new ThreadByExtend();
myThread1.start();
myThread2.start();
myThread3.start();
myThread4.start();
myThread1.join();
myThread2.join();
myThread3.join();
myThread4.join();
}
}
Java面试题:
为什么必须调用Thread start方法,不能直接调用Thread的run方法创建?
Thead的run方法相当于主线程的main方法,创建线程必须由系统通过start方法来调用
start方法是一种native方法,即本地方法,Start方法通过系统调用注册新的线程,安排好上线文, 才会执行run方法
如果直接执行run方法,则仍然是在主线程中,将run作为一个普通的方法调用,返回后仍然是在主线程
每一个Thread对象的start方法只能调用一次。
下图示意了直接调用run方法 和 调用 start 方法的区别:
二、实现Runable接口
package week3.demo;
public class ThreadByRunnable implements Runnable{
public static volatile int count = 0;
public void run() {
for(int i=0;i<50;i++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "sold "+(i+1)+" tickets total Sold:" + (++count));
}
}
public static void main(String[] argv) throws InterruptedException{
ThreadByRunnable myRunnable = new ThreadByRunnable();
Thread thread1 = new Thread(myRunnable, "Thread1");
Thread thread2 = new Thread(myRunnable, "Thread2");
Thread thread3 = new Thread(myRunnable, "Thread3");
Thread thread4 = new Thread(myRunnable, "Thread4");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread1.join();
thread2.join();
thread3.join();
thread4.join();
}
}
覆写Runnable接口相比继承Thread类的好处?
a.首先,覆写Runnable接口实现多线程可以避免单继承局限,
因为我们的线程工作对象可能是别的类的子类,那么强制必须是Thread类的子类就会带来很大的麻烦
b. 通过runnable方式,多个线程可以共享同一个对象,大家可以对比一下,我们在继承Thread的方式中,线程之间因为是不同的对象,那么共享数据就只能用静态变量的方式才能使得多个线程之间可见。
而在runnable这个例子里面count改成非静态变量仍然是可见的, 因为两个thread的构造都是同一个runnable对象
三、Callable与FutureTask
package week3.demo;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadByCallable implements Callable{
private static int count = 0;
@Override
public String call() {
for(int i=0;i<50;i++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "sold "+(i+1)+" tickets total Sold:" + (++count));
}
return Thread.currentThread().getName()+"sale out";
}
public static void main(String[] argv) throws InterruptedException, ExecutionException {
Callable<String> callable = new ThreadByCallable();
FutureTask<String> futureTask1 = new FutureTask<String>(callable);
FutureTask<String> futureTask2 = new FutureTask<String>(callable);
FutureTask<String> futureTask3 = new FutureTask<String>(callable);
FutureTask<String> futureTask4 = new FutureTask<String>(callable);
Thread thread1 = new Thread(futureTask1);
Thread thread2 = new Thread(futureTask2);
Thread thread3 = new Thread(futureTask3);
Thread thread4 = new Thread(futureTask4);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
String retVal1 = futureTask1.get();
String retVal2 = futureTask2.get();
String retVal3 = futureTask3.get();
System.out.println("Return value "+retVal1);
System.out.println("Return value "+retVal2);
System.out.println("Return value "+retVal3);
thread1.join();
thread2.join();
thread3.join();
thread4.join();
}
}
通过callable和future来创建thread需要四个步骤
1、创建Callable接口实现类,并实现call()方法,该方法将作为线程执行体,且该方法有返回值,再创建Callable实现类的实例;
2、使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值;
3、使用FutureTask对象作为Thread对象的target创建并启动新线程;
4、调用FutureTask对象的get()方法来获得子线程执行结束后的返回值。
Java面试题:Callable与Future、FutureTask
为何引入Callable接口
提供执行的返回值, 通过泛型方式Callable可以返回任意类型。
Java 1.5引入的Callable接口,可以提供执行的返回值。
从这里可以看出,完全可以提供一个Callable对象作为Thread的target,而该线程的线程执行体就是call()方法。但问题是:Callable接口是JAVA新增的接口,而且它不是Runnable接口的子接口,所以Callable对象不能直接作为Thread的target。还有一个原因就是:call()方法有返回值,call()方法不是直接调用,而是作为线程执行体被调用的,所以这里涉及获取call()方法返回值的问题。
FutureTask的作用
FutureTask同时实现了Future接口和Runnable接口,同时接受以Callable作为构造, 这样FutureTask就可以成为Thread类的target(提供thread需要的run方法),同时提供Callable的返回值处理Future接口, 指的是异步调用中,被调用者在将来会返回的值。
四、线程池
package week3.demo;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolCallable implements Callable {
private static int count = 0;
public String call() {
for(int i=0;i<50;i++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "sold "+(i+1)+" tickets total Sold:" + (++count));
}
return "sale out";
}
public static void main(String[] argv) throws InterruptedException, ExecutionException {
ExecutorService ex = Executors.newFixedThreadPool(4);
for (int i = 0; i < 4; i++) {
ex.submit(new ThreadPoolCallable());
}
ex.shutdown();
}
}
package week3.demo;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadPoolRunnable implements Runnable{
private static volatile AtomicInteger count = new AtomicInteger(0);
public void run() {
for(int i=0;i<50;i++) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " sold "+(i+1)+" tickets total Sold:" + count.incrementAndGet());
}
}
public static void main(String[] argv) throws InterruptedException, ExecutionException {
ExecutorService ex = Executors.newFixedThreadPool(4);
for (int i = 0; i < 4; i++) {
ex.submit(new ThreadPoolRunnable());
}
ex.shutdown();
}
}
如上代码所述, 通过ExecutorService 可以新建线程池, 用submit()方法可以将 runnable 对象 交付线程池运行
结束时调用shutdown()
线程池里也可以直接submit callable对象