package com.data.entity;
public class MyThread extends Thread{
public String name;
public MyThread() {}
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
//super.run();
for (int i=0;i<=100;i++) {
System.out.println(this.name+"===="+i);
}
}
}
package com.data.entity;
public class MyRunnable implements Runnable{
public String name;
public MyRunnable() {}
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
for (int i=1;i<=100;i++) {
System.out.println(this.name+"====="+i);
}
}
}
import com.data.entity.MyRunnable;
import com.data.entity.MyThread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class text7 {
public static void main(String[] args) {
//继承Thread, 重写run方法
// Thread t1 = new MyThread("t1");
// Thread t2 = new MyThread("t2");
// t1.start();
// t2.start();
// //t1.run();
// //t2.run();
//====================================================
//实现Runnable,重写run方法. 在Thread对象的构造中传入任务对象 线程任务
//推荐使用
// Runnable r = new MyRunnable("t1"); //先创建任务对象
// Thread t1 = new Thread(r); //将任务对象传入线程对象
// t1.start();
//
// Runnable r2 = new MyRunnable("t2"); //先创建任务对象
// Thread t2 = new Thread(r2); //将任务对象传入线程对象
// t2.start();
//====================================================
//线程池 推荐使用
// //ExecutorService es1= Executors.newCachedThreadPool(); //不固定数量线程池
// ExecutorService es1= Executors.newFixedThreadPool(2); //设置线程数量为
// Runnable r1=new Runnable() {
// @Override
// public void run() {link_for("t1:: ===");}
// };
// Runnable r2=new Runnable() {
// @Override
// public void run() {link_for("t2> ===");}
// };
// es1.submit(r1); //执行
// es1.submit(r2); //执行
//
// es1.shutdown(); //关闭线程
//====================================================
//任务只会执行一次时,可以通过匿名内部类或者lambda简化书写
// Thread t1=new Thread(new Runnable() {
// @Override
// public void run() {link_for("t1:: ===");}
// });
// Thread t2=new Thread(()->{link_for("t2> ===");});
// Thread t3=new Thread(()->{link_for("t3> ===");});
//
// t1.start();
// t2.start();
// t3.start();
//====================================================
//线程参数返回
ExecutorService es1= Executors.newCachedThreadPool(); //不固定数量线程池
Callable<Integer> c1=new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int sum=0;
for(int i=0;i<100;i++){
sum+=i;
}
return sum;
}
};
try{
Future<Integer> f=es1.submit(c1);
System.out.println(f.get());
System.out.println(es1.submit(c1).get());
es1.shutdown();
}catch (Exception e){
System.out.println(e.toString());
}
//====================================================
}
public static void link_for(String ss){
for (int i = 101; i <=200 ; i++) {
System.out.println(ss+i);
}
}
}