实现Callable接口的实现方式区别于其他两种,多了个返回值,并且需要创建执行服务才能实现多线程,如:
package Test; import MyTool.*; import java.util.concurrent.*; public class Test5 implements Callable静态代理{ String url; String name; Test5(String url,String name){ this.url=url; this.name=name; } @Override public Boolean call() throws Exception { MyIo my=new MyIo(); //下载方法 my.download(url,name); return true; } public static void main(String[] args) throws ExecutionException, InterruptedException { Test5 te1=new Test5("https://img-operation.csdnimg.cn/csdn/silkroad/img/1607569674685.png","图片一"); Test5 te2=new Test5("https://img-operation.csdnimg.cn/csdn/silkroad/img/1607569674685.png","图片二"); Test5 te3=new Test5("https://img-operation.csdnimg.cn/csdn/silkroad/img/1607569674685.png","图片三"); //创建执行服务 ExecutorService ser=Executors.newFixedThreadPool(3); //提交执行服务 Future f1=ser.submit(te1); Future f2=ser.submit(te2); Future f3=ser.submit(te3); //获取结果 boolean jg1=f1.get(); boolean jg2=f2.get(); boolean jg3=f3.get(); //关闭服务 ser.shutdown(); } }
静态代理也就是帮助某个对象代理一些事务,让对象更加方便如:
package Test;
public class Test4 {
public static void main(String[] args) {
MyJh mj=new MyJh();
Jhs jhs=new Jhs(mj);
jhs.state();
}
}
interface jh{
void state();
}
class MyJh implements jh{
@Override
public void state() {
System.out.println("超级开心");
}
}
class Jhs implements jh{
private jh a;
public Jhs(jh a){
this.a=a;
}
@Override
public void state() {
zq();
this.a.state();
zh();
}
private static void zq(){
System.out.println("布置场地");
}
private static void zh(){
System.out.println("上交工资");
}
}
多线程基础练习
1.模拟三个对象强火车票(可能票数会重复)
package Test;
public class Tang3 implements Runnable{
//票数
int ps=10;
@Override
public void run() {
while(true){
if (ps<=0){
break;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到第"+ps+"张票");
ps--;
}
}
public static void main(String[] args) {
Tang3 tang=new Tang3();
new Thread(tang,"小明").start();
new Thread(tang,"张三").start();
new Thread(tang,"黄牛党").start();
}
}
2.实现龟兔赛跑
package Test;
public class Test6 implements Runnable{
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
pd(i);
sj(i);
System.out.println(Thread.currentThread().getName()+"正跑到了"+i+"步");
}
}
//判断胜利者的方法
public static void pd(int i){
if (i>=100){
System.out.println("胜利者是"+Thread.currentThread().getName());
System.exit(1);
}
}
//使兔子睡觉的方法
public static void sj(int i){
if (Thread.currentThread().getName().equals("兔子")&&i==50){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test6 test1=new Test6();
Test6 test2=new Test6();
new Thread(test1,"兔子").start();
new Thread(test2,"乌龟").start();
}
}


![java复习第十六天[多线程二] java复习第十六天[多线程二]](http://www.mshxw.com/aiimages/31/723793.png)
