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(); } } }
时间: 2024-11-07 19:20:24