Java-多线程

 

 

 

 这里是关于多线程的实现的代码:

Thread:

public class threadtest extends  Thread {
    @Override
    public  void run(){
        //继承Thread 重写run方法
        System.out.println(getName()+"你好");
    }
}

 测试一下:

public class test {
    public static void main(String[] args) {
        //继承Thread 重写run方法
threadtest t1=new threadtest();
//创建线程
t1.start();
//开启线程
t1.setName("线程1");
threadtest t2=new threadtest();
t2.start();
t2.setName("线程2");
    }
}
j

 Runnable方法:

public class myrunnable implements Runnable{
    @Override
    public void run() {
        //实现接口 重写方法
        for (int i = 0; i < 10; i++) {
            Thread tt = Thread.currentThread();
            System.out.println(tt.getName()+"你好");
        }
    }
}

 测试一下:

public class myrunabletest {
    public static void main(String[] args) {
        myrunnable m1=new myrunnable();
        //先去是实现接口Runnable 创建任务
        Thread t1=new Thread(m1);
        //创建线程 执行任务
  Thread t2=new Thread(m1);
  t1.setName("线程1");
  t2.setName("线程2");
  //设置线程的名字
  t1.start();
  t2.start();
  //开启线程
    }
}

 下面Callable 以及future

import java.util.concurrent.Callable;

public class mycallable implements Callable<String>
//实现接口 并且指定泛型
{
    @Override
    public String call() throws Exception {
        for (int i = 0; i < 10; i++) {
            System.out.println("测试111");
        }
        return null;
    }
}

测试一下:

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class mycallabletext {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        mycallable m1=new mycallable();
        //创建任务
        FutureTask <String> f1=new FutureTask<>(m1);
        //获取任务的结果
        Thread t1=new Thread(f1);
        //创建线程
        t1.start();
        //开启线程
        String s = f1.get();
        System.out.println(s);
        //返回结果
    }
}

这几种方式的不同 优缺点也不同  在上面的思维导图中标注了 这里不过多解释  可以直接看注释

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

胖虎爱Java

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值