public class ThreadTest{
public static void main(String[] args){
MyThread thread =newMyThread();//3、创建子类对象
thread.start();//4、对象.start()}}
class MyThread extends Thread{//1、创建子类继承Thread
@Override
public void run(){//2、重写run()for(int i =0; i <100; i++){
System.out.println(i);}}}
2、 实现Runnable接口
定义子类,实现Runnable接口。
子类中重写Runnable接口中的run方法。
通过Thread类含参构造器创建线程对象。
将Runnable接口的子类对象作为实际参数传递给Thread类的构造器中。
调用Thread类的start方法:开启线程,调用Runnable子类接口的run方法。
public class ThreadTest1{
public static void main(String[] args){
MyThread1 myThread1 =newMyThread1();//3、创建子类对象
Thread thread =newThread(myThread1);//4、将子类对象作为参数传递给Thread类的构造器中
thread.start();//5、调用start方法}}
class MyThread1 implements Runnable{//1、实现接口
public void run(){//2、重写run()for(int i =0; i <100; i++){
System.out.println(i);}}}
class NumThread implements Callable{//1、创建一个实现Callable接口的实现类
public Object call() throws Exception {//2、实现call(),将此线程需要执行的操作声明在call()中
int sum =0;for(int i =1; i <100; i++){if(i%2==0){
System.out.println(i);
sum += i ;}}return sum;}}
public class NewThreadTest1{
public static void main(String[] args){
NumThread n1 =newNumThread();//3、创建Callable接口实现类的对象
FutureTask futureTask =newFutureTask(n1);//4、将Callable接口实现类的对象作为参数传到FutureTask//构造器中,创建FutureTask类的对象newThread(futureTask).start();//5、将FutureTask类的对象作为参数传递到Thread构造器中,创建Thread对象并调用start()try{//6、获取Callable中call()返回值//get()返回值即为FutureTask构造器参数Callable实现类重写的call()返回值
Object sum = futureTask.get();
System.out.println(sum);}catch(InterruptedException e){
e.printStackTrace();}catch(ExecutionException e){
e.printStackTrace();}}}
class NewThread implements Runnable{
public void run(){for(int i =0; i <100; i++){if(i%4==0){
System.out.println(Thread.currentThread().getName()+":"+i);}}}}
class NewThread1 implements Runnable{
public void run(){for(int i =0; i <100; i++){if(i%8==0){
System.out.println(Thread.currentThread().getName()+":"+i);}}}}
public class ThreadPool{
public static void main(String[] args){//1、提供指定数量的线程池
ExecutorService service = Executors.newFixedThreadPool(10);//2、执行指定的线程操作,需要提供实现Runnable接口或者Callable接口的对象
service.execute(newNewThread());//适用于Runnable接口
service.execute(newNewThread1());//适用于Runnable接口// service.submit(); //适用于Callable接口//3、关闭线程连接池
service.shutdown();}}