多线程初探(线程的创建)

来源:互联网 发布:java识别验证码字母 编辑:程序博客网 时间:2024/05/22 01:27

多线程的实现方法:

方法一

public class ThreadDemo1 extends Thread{/** * @param args * 通过继承Thread实现多线程 */private static int threadcount=0;private  int threadNumber=++threadcount;public ThreadDemo1(){System.out.println("makeing"+threadNumber);}public void run(){System.out.println("i am thread "+threadNumber);}public static void main(String[] args) {// TODO Auto-generated method stubfor(int i=0;i<5;i++){new ThreadDemo1().start();System.out.println("all the threads started");}}}


方法二


public class ThreadDemo2 {/** * @param args * 通过实现runnable实现多线程 */public static void main(String[] args) {// TODO Auto-generated method stub//创建任务Runnable task1=new PrintChar('a', 200);Runnable task2=new PrintChar('b', 200);Runnable task3=new PrintNum(300);//创建线程Thread thread1=new Thread(task1);Thread thread2=new Thread(task2);Thread thread3=new Thread(task3);System.out.println("all the threads started");//开始线程thread1.start();        thread2.start();        thread3.start();}}class PrintChar implements Runnable{private char charToPrint;private int times;public PrintChar(char charToPrint, int times) {// TODO Auto-generated constructor stubthis.charToPrint=charToPrint;this.times=times;}@Overridepublic void run() {// TODO Auto-generated method stubfor(int i=0;i<times;i++){System.out.print(charToPrint);}}}class PrintNum implements Runnable{private int num;public PrintNum(int num) {// TODO Auto-generated constructor stubthis.num=num;}@Overridepublic void run() {// TODO Auto-generated method stubfor(int i=0;i<=num;i++){System.out.print(i+" ");}}}


线程池

import java.util.concurrent.*;public class ExecutorDemo {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubExecutorService excutor=Executors.newFixedThreadPool(3);//创建包含3个线程的线程池excutor.execute(new PrintChar('a', 1000));excutor.execute(new PrintChar('b',1000));excutor.execute(new PrintNum(1000));excutor.shutdown();}}




0 0