Java的多线程创建方法
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){
//这里新建了两个Thread对象 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的方式创建
注:区别于第一种方法,这里可以达到两个线程共享变量i的目的。
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() + " " + "当前j的值是:" + j); if(j==20){ RunnableEx REx=new RunnableEx();
//这里也新建了两个Thread对象,但是里面的Target是同一个Runnable实现类对象 Thread thread1 = new Thread(REx, "实例1"); Thread thread2 = new Thread(REx, "实例2"); thread1.start(); thread2.start(); } } } }
3. 通过实现Callable接口的方式创建(这是一个具有返回值的创建方式)
注:FutureTask只能启动一个线程
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{
//这里的get()方法可以获取到子线程的返回值,而且在执行时会中断main线程 System.out.println("线程的返回值:" + task.get()); }catch(Exception ex){ ex.printStackTrace(); } } }
本文来自博客园,作者:月色深潭,交流群:733423266,转载请注明原文链接:https://www.cnblogs.com/moonpool/p/5472549.html