码迷,mamicode.com
首页 > 编程语言 > 详细

Java的多线程创建方法

时间:2016-05-09 08:34:48      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

1. 直接使用Thread来创建

package com.test.tt;

public class ThreadEx extends Thread{
    private int j;
    
    public void run(){
        for(j=0; j<100;j++){
            System.out.println("当前的线程名称是:"+ getName() + " " +  "当前j的值是:" + j);
        }
    }
    

    public static void main(String[] args) {
        for(int h=0; h<100;h++){
            
            if(h==20){
                ThreadEx  threadTest1= new ThreadEx();
                ThreadEx  threadTest2= new ThreadEx();
                threadTest1.start();
                threadTest2.start();
            }
            
            System.out.println("当前的线程名称是:"+ Thread.currentThread().getName() + " " +  "当前h的值是:" + h);
            
        }
        

    }

}

2. 通过实现Runnable接口,并将Runnable实现对象作为Thread的Target的方式创建

package com.test.tt;

public class RunnableEx implements Runnable{
    
    private int i;
    @Override
    public void run() {
        for(i=0; i<100;i++){
            System.out.println("当前的线程名称是:"+ Thread.currentThread().getName() + " " +  "当前i的值是:" + i);
        }
        
    }

    public static void main(String[] args) {
        for(int j=0;j<100;j++){
            System.out.println("当前的线程名称是:"+ Thread.currentThread().getName() + " " +  "当前i的值是:" + j);
            if(j==20){
                RunnableEx REx=new RunnableEx();
                Thread thread1 = new Thread(REx, "实例1");
                Thread thread2 = new Thread(REx, "实例2");
                thread1.start();
                thread2.start();
            }                        
        }

    }



}

3. 通过实现Callable接口的方式创建(这是一个具有返回值的创建方式)

package com.test.tt;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class CallableEx implements Callable{
    @Override
    public Object call() throws Exception {
        int i =0;
        for(;i<1000;i++){
            System.out.println("当前的线程名称是:"+ Thread.currentThread().getName() + " " +  "当前i的值是:" + i);            
        }
        return i;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        CallableEx CEx = new CallableEx();
        FutureTask<Integer> task = new FutureTask<Integer>(CEx);
        
        for(int j=0;j<1000;j++){
            System.out.println("当前的线程名称是:"+ Thread.currentThread().getName() + " " +  "当前i的值是:" + j);
            if(j==200){
                Thread thread1 = new Thread(task, "实例1");
                thread1.start();
            }            
        }
        
        try{
            System.out.println("线程的返回值:" + task.get());
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }



}

 

Java的多线程创建方法

标签:

原文地址:http://www.cnblogs.com/moonpool/p/5472549.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!