多线程创建
1.继承Thread类
public class TestThread 1 extends Thread{
//重写run方法,
@override
public void run(){
for(int i=0;i<100;++i){
System.out.println("reading"+i);
}
}
public static void main(String[] args){
for(int i=0;i<20;++i){
System.ot.println("eating"+i);
}
//创建线程
TestThread1 testThread1=new TestThread1();
//调用start方法,启动线程
testThread1.start();
}
}
2.实现Runnable接口
public class TestThread2 implements Runnable{
//重写run方法,
@override
public void run(){
for(int i=0;i<100;++i){
System.out.println("reading"+i);
}
}
public static void main(String[] args){
for(int i=0;i<20;++i){
System.ot.println("eating"+i);
}
/*
//创建线程
TestThread1 testThread1=new TestThread1();
//调用start方法,启动线程
testThread1.start();
*/
//创建实现类对象
TestThread2 testThread2=new Testthread2();
//创建线程,通过线程对象开启线程,底层原理:代理
Thread thread=new Thread(testThread2);
//启动线程
thread.start();
}
}
3.实现Callable接口
public class TestThread3 implements Callable<Boolean>{//需要返回值
//重写run方法,
@override
public Boolean call(){
for(int i=0;i<100;++i){
System.out.println("reading"+i);
}
}
public static void main(String[] args){
for(int i=0;i<20;++i){
System.ot.println("eating"+i);
}
/* 继承Thread类
//创建线程
TestThread1 testThread1=new TestThread1();
//调用start方法,启动线程
testThread1.start();
*/
/* 实现Runnable接口
//创建实现类对象
TestThread2 testThread2=new Testthread2();
//创建线程,通过线程对象开启线程,底层原理:代理
Thread thread=new Thread(testThread2);
//启动线程
thread.start();
*/
TeatThread3 t1=new TestThread3();
TeatThread3 t1=new TestThread3();
TeatThread3 t1=new TestThread3();
//创建服务
ExecutorService ser=Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1=ser.submit(t1);
Future<Boolean> r2=ser.submit(t2);
Future<Boolean> r3=ser.submit(t3);
//获取结果
boolean rs1=r1.get();
boolean rs2=r2.get();
boolean rs3=r3.get();
//关闭服务
ser.shutdownNow();
}
}
4.静态代理
/*
new Thread(new TestThread()).start();就是代理模式实现的,Thread是一个代理,TestThread就是真实角色
*/
//只需要自己完成核心任务,千篇一律的任务交给代理去做
//比如,具体的人只需要结婚,结婚之前之后工作由代理完成
public class StaticProxy{
//将真实对象传入代理对象,由代理对象执行操作
WeddingCompany w=new WeddingCompany(new You);
w.HappyMarry();
}
interface Maryy{
void HappyMarry();
}
//真是角色
class You implements Marry{
public void HappyMarry(){
System.out.println("结婚");
}
}
//代理角色
class WeddingCompany implements Marry{
private Marry target;
public WeddingCompany(Marry targrt){
this.target=targrt;
}
public void HappyMarry(){
before();
this.HappyMaryy();
after();
}
public void before(){
System.out.println("结婚之前");
}
public void after(){
System.out.println("结婚之后");
}
}