java 创建线程
方法一:
package tao.thread.ch01; public class MyThread extends Thread{ public MyThread(String name){ super(name); } public void run() { for(int i=0;i<10;i++){ // 输出线程名字 System.out.println(this.getName()); } } public static void main(String[] args){ for(int i=0;i<5;i++){ // 创建五个线程 new MyThread("Thread_"+i).start(); } } }
方法二:
package tao.thread.ch01; public class MyThreadTarget implements Runnable { public void run() { for (int i = 0; i < 10; i++) { System.out.println(Thread.currentThread().getName()); } } /** * @param args */ public static void main(String[] args) { for(int i=0;i<5;i++){ new Thread(new MyThreadTarget(),"Thread_"+i).start(); } } }
方法三: 通过 java 线程池创建
package tao.thread.ch01; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * * @author wangtao * * 从执行结果可以看书,线程池中只生成了两个线程对象,100个线程目标对象共享他们 * 使用JDK提供的线程池一般分为三个步骤: * 1:创建线程目标对象 * 2:使用Executors创建线程池,返回一个ExecutorService类型的对象 * 3:使用线程池执行线程目标对象, 结束线程池中的线程 */ public class ThreadPoolTest { public static void main(String[] args) { // 线程池中创建两个线程 ExecutorService es = Executors.newFixedThreadPool(2); // 创建100个线程目标对象 for(int i=0;i<100;i++){ Runnable run = new Runner(i); // 执行线程目标对象 es.execute(run); } // 结束线程池中的线程 es.shutdown(); } } // 线程目标对象 class Runner implements Runnable{ int index = 0; public Runner(int index){ this.index = index; } @Override public void run(){ long time = (long) (Math.random()*1000); // 输出线程的名字和使用目标对象及休眠时间 System.out.println("线程: "+Thread.currentThread().getName()+" 目标对象 "+index); try { Thread.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } } }