public class Test implements Runnable{
public void run() {
System.out.println("dadadadd");
}
public static void main(String[] args) {
Test a = new Test();
//a.run(); 错误写法
//Thread 需要一个线程对象,然后它用其中的代码向系统申请CPU时间片
Thread thread = new Thread(a);
Thread thread1 = new Thread(a);
Thread thread2 = new Thread(a);
Thread thread3 = new Thread(a);
thread.start();
thread1.start();
thread2.start();
thread3.start();
}
}
线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyThread {
int threads =4 ;
ExecutorService es = Executors.newFixedThreadPool(threads);//轻量级
//用于少数几个长期运行任务的线程池,重用已有的线程,不会创建新的线程
ExecutorService service = Executors.newCachedThreadPool();
//动态线程池,长期不用的线程将从线程池删除,重用以前构造的线程
}