1、实现线程的方法:(1)继承Thread类重写run方法
(2)实现Runnable接口重写un方法
(3)实现Callable接口通过FutureTask包装器来创建Thread线程
(4)利用线程池(newCachedThreadPool、newFixedThreadPool )
1、继承Thread类
(1)线程类 public class MyThread extends Thread { public void run() { //不会创建新的线程,相当于只是一个普通方法,由当前线程来调用 System.out.println("MyThread.run()"); } } (2)测试类 MyThread myThread1 = new MyThread(); MyThread myThread2 = new MyThread(); myThread1.start(); //会创建新的线程 myThread2.start();
start方法是创建了新的线程,在新的线程中执行
run方法是在主线程中执行该方法,和调用普通方法一样
2、实现Runnable接口
当前类如果已经继承一个父类,可以通过实现Runnable接口实现线程的创建
(1)线程类
public class MyThread extends A implements Runnable {
public void run() {
System.out.println("线程执行");
}
(2)测试类
MyThread s1=new MyThread();
Thread t1 =new Thread(s1);
t1.start();
}
3、实现Callable接口
(1)线程类
public class MyThread extends OtherClass implements Callable<Integer> { public Integer call() throws Exception { return 1; }
(2)测试类
Callable<Integer> oneCallable = new SomeCallable<Integer>(); //由Callable<Integer>创建一个FutureTask<Integer>对象: FutureTask<Integer> oneTask = new FutureTask<Integer>(oneCallable); //FutureTask<Integer>是一个包装器,它通过接受Callable<Integer>来创建,它同时实现了Future和Runnable接口。 Thread oneThread = new Thread(oneTask); oneThread.start(); 4、 newCachedThreadPool线程池
(1)匿名类方式
ExecuteService a=Executors.newCachedThreadPool();
a.execute(new Runnable(){
public void run(){
System.out.println("一个线程");
}
});
(2)普通类方式
测试类
ExecutorService service = Executors.newFixedThreadPool(2);//包含2个线程对象
MyRunnable r = new MyRunnable();
service.submit(r);
线程类
public class MyRunnable implements Runnable { public void run() { System.out.println("一个线程"); } }