Java对多线程的支持
Java创建多线程的3种常用方法:
1)继承Thread类
重写Thread类的run方法,创建Thread子类实例,启动线程。
例如:
- /*
- * @author wxismeit@163.com wangxu
- */
- public class TreadOfextends extends Thread{
- private int i;
- //重写run()方法
- public void run(){
- for(i=0; i<50; i++){
- System.out.println(getName() + " " + i);
- //继承Thread类时直接使用this即可获取当前线程
- }
- }
- public static void main(String[] args) {
- System.out.println(Thread.currentThread().getName());
- for(int i=0; i<50; i++){
- if(i == 10){
- //直接通过创建类对象来调用start()方法
- new TreadOfextends().start();
- new TreadOfextends().start();
- }
- }
- }
- }
2)实现Runnable接口
重写run()方法,创建Runnable实例作为Thread的target。
例如:
- public class ThreadOfRun implements Runnable {
- private int i;
- //实现Runnable接口中的run()方法
- public void run() {
- for(i=0; i<50; i++) {
- System.out.println(Thread.currentThread().getName() + " " + i);
- //通过实现接口来实现多线程 就不能通过this关键字来获取当前进程
- }
- }
- public static void main(String[] args) {
- for(int i=0; i<50; i++) {
- System.out.println(Thread.currentThread().getName() + " " + i);
- if(i == 10) {
- ThreadOfRun tor = new ThreadOfRun();
- //此处需要通过Thread的构造方法来new线程
- new Thread(tor , "线程1").start();
- new Thread(tor , "线程2").start();
- }
- }
- }
- }
3)Java 5以后可以通过更强大的手段——实现Callable接口
使用FutureTask对象作为Thread的对象的target创建并启动新线程
- import java.util.concurrent.Callable;
- import java.util.concurrent.FutureTask;
- public class ThreadOfCallble implements Callable<Integer> {
- //支持泛型
- public Integer call() throws Exception {
- int i;
- for(i=0; i<50; i++) {
- System.out.println(Thread.currentThread().getName() + " " + i);
- }
- return i;//有返回值
- }
- public static void main(String[] args) {
- //创建Callable对象
- ThreadOfCallble toc = new ThreadOfCallble();
- //通过FutureTask来包装Callable对象
- FutureTask<Integer> ft = new FutureTask<Integer>(toc);
- for(int i=0; i<50; i++) {
- if(i ==10) {
- new Thread(ft , "NewThread").start();
- }
- }
- try {
- //得到新线程的返回值
- System.out.println("子线程的返回值 : " + ft.get());
- }catch(Exception e) {
- e.printStackTrace();
- }
- }
- }
三种方式的对比 : 后两种方法非常适合多个相同的线程来处理同一份资源的情况,可以将CPU,代码和数据分开,比较符合面向对象的思想,而且还可以继承其他类,所以一般采用后两种方法。
oin线程
当在某个程序执行中调用其他线程的join方法时,条用线程将被阻塞,直至被join线程执行完为止。
- <pre class="java" name="code">public class ThreadOfjoin extends Thread {
- public ThreadOfjoin(String name) {
- super(name);
- }
- public void run() {
- for(int i=0; i<50; i++) {
- System.out.println(getName());
- }
- }
- public static void main(String[] args) {
- new ThreadOfjoin("NewThread").start();
- for(int i=0; i<50; i++) {
- if(i == 10) {
- ThreadOfjoin toj = new ThreadOfjoin("JoinedThread");
- toj.start();
- try {
- toj.join();//主线程调用了toj的join方法,需要等toj执行完主线程才能执行
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println(Thread.currentThread().getName());
- }
- }
- }