java多线程

创建一个线程

Java 提供了三种创建线程的方法:

  • 通过继承 Thread 类本身;

public class MyThread extends Thread{
    // 重写run方法  里面放要执行的代码
    @Override
    public void run() {
        for (int i = 0; i < 100; i++){
            System.out.println("线程" + Thread.currentThread().getName() + "运行,i = " + i);
        }
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread t1=new MyThread();
        MyThread t2 = new MyThread();

        t1.setName("线程1");
    
        t2.setName("线程2");
    
        t1.start();
    
        t2.start();
    
    }

}
  • 通过实现 Runnable 接口;

        1.自定义一个类实现Runnable接口

        2.重写run方法

        3.创建自己的类对象

        4.创建一个Thread类的对象,并开启线程

public class MyRun implements Runnable{
    @Override
    public void run(){
        for (int i = 0; i < 100; i++){

            System.out.println("线程" + Thread.currentThread().getName() + "运行,i = " + i);
        }
    }

}
public class ThreadDemo2 {
    public static void main(String[] args) {
        // 创建线程任务
        MyRun run=new MyRun();
        // 创建线程
        Thread t = new Thread(run);
        t.setName("线程1");
        t.start();

    }

}
  • 通过 Callable 和 Future 创建线程。

可以获得多线程运行的结果

import java.util.concurrent.Callable;

public class MyCallable implements Callable<Integer> {
    @Override
    public Integer call()throws Exception {
        //求1-100之间的和
        int sum=0;
        for(int i=1;i<=100;i++){
            sum+=i;
        }
        return sum;
    }
}
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreadDemo3  {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建MyCallable对象(表示多线程要执行的任务)
        MyCallable mc = new MyCallable();
        //创建一个FutureTask对象(作用管理多线程运行的结果)
        FutureTask<Integer> ft=new FutureTask(mc);
        //创建线程对象
        Thread t1=new Thread(ft);
        //启动线程
        t1.start();
        //获取线程运行结果
        Integer result=ft.get();
        System.out.println(result);
    
    }

}

守护线程

作用在于主线程结束后,自动结束

t2.setDaemon(true);

出让线程

Thread.yield();  
使得重新抢夺线程 ,让执行更均匀一些

插入线程

t1.join();  将t1插入让此进程先执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值