java多线程之线程创建(一)

一、普通方法调用与多线程

在这里插入图片描述

二、程序,进程及线程

程序:是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念。
进程:是程序的一次执行过程,是一个动态的概念。是系统资源分配的单位。
线程:通常在一个进程中可以包含若干个线程,一个进程至少包含一个线程。线程是CPU调度和执行的基本单位。

三、线程创建

在这里插入图片描述
1.创建线程的第一种方式
(1)自定义线程类继承Thread类
(2)重写run()方法,编写线程执行体
(3)创建线程对象,调用start()方法启动线程

package com.atguigu.demo01;

//创建线程方式一:继承Thread类,重写 run方法,调用start开启线程
//总结:线程开启不一定会立即执行,由cpu调度执行
public class TestThread extends Thread {

    @Override
    public void run() {
        for(int i=1;i<=10;i++){
            System.out.println("线程:"+i);
        }
    }

    //主线程
    public static void main(String[] args) {
        TestThread testThread=new TestThread();
        //testThread.start();两个线程并发执行
        testThread.run();//先执行run方法

        for(int i=1;i<=10;i++){
            System.out.println("主线程:"+i);
        }
    }
}

文件下载案例:

package com.atguigu.demo02;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThread extends Thread {
    private String url;
    private String name;

    public TestThread(String url, String name) {
        this.url = url;
        this.name = name;
    }

    public void run()  {
        WebDownLoader webDownLoader = new WebDownLoader();
        webDownLoader.downLoader(url, name);
        System.out.println("下载了图片,名为:" + name);
    }

    public static void main(String[] args) throws Exception {
        TestThread t1 = new TestThread("http://bos.pgzs.com/rbpiczy/Wallpaper/2012/1/6/aeae710d55ed4afab8a5993d457634bc-2.jpg", "cat1.jpg");
        TestThread t2 = new TestThread("http://g.hiphotos.baidu.com/zhidao/pic/item/8435e5dde71190efc8f16ea9cd1b9d16fdfa60ba.jpg", "cat2.jpg");
        TestThread t3 = new TestThread("http://www.chabeichong.com/images/2014/07/11-2347573.jpg", "cat3.jpg");

  	   t1.start();
       t2.start();
       t3.start();
       
       //实现runnale接口时的启动方式
      /* new Thread(t1).start();
       new Thread(t2).start();
       new Thread(t3).start();*/
    }
}

//下载器
class WebDownLoader{
    //下载方法
    public void downLoader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件io异常");
        }
    }
}

2.创建线程的第二种方式
(1)自定义线程类实现Runnable接口
(2)实现run()方法,编写线程执行体
(3)创建线程对象,调用start()方法启动线程

package com.atguigu.demo01;

//创建线程的第二种方式
public class TestThread2 implements Runnable {
    public void run() {
        for(int i=1;i<=20;i++){
            System.out.println("run方法执行了:"+i);
        }
    }

    public static void main(String[] args) {
        TestThread2 thread2=new TestThread2();
        new Thread(thread2).start();
        for(int i=1;i<=20;i++){
            System.out.println("main方法执行了:"+i);
        }
    }
}

在这里插入图片描述
多个线程同时操作同一个对象,会出现线程安全问题,如下代码所示:

package com.atguigu.demo01;

//多个线程同时使用一个对象:存在线程安全问题
public class TestThread3 implements Runnable {
    private int ticket=10;

    public void run() {
        while (true){
            if(ticket<0){
                break;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"拿到了第"+ticket--+"张票");
        }
    }

    public static void main(String[] args) {
        TestThread3 thread2=new TestThread3();
        new Thread(thread2,"张三").start();
        new Thread(thread2,"李四").start();
        new Thread(thread2,"王五").start();
}
}

3.创建线程的第三种方式
在这里插入图片描述

package com.atguigu.demo02;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThread implements Callable<Boolean> {
    private String url;
    private String name;

    public TestThread(String url, String name) {
        this.url = url;
        this.name = name;
    }

    public Boolean call() throws Exception {
        WebDownLoader webDownLoader = new WebDownLoader();
        webDownLoader.downLoader(url, name);
        System.out.println("下载了图片,名为:" + name);
        return true;
    }

    public static void main(String[] args) throws Exception {
        TestThread t1 = new TestThread("http://bos.pgzs.com/rbpiczy/Wallpaper/2012/1/6/aeae710d55ed4afab8a5993d457634bc-2.jpg", "cat1.jpg");
        TestThread t2 = new TestThread("http://g.hiphotos.baidu.com/zhidao/pic/item/8435e5dde71190efc8f16ea9cd1b9d16fdfa60ba.jpg", "cat2.jpg");
        TestThread t3 = new TestThread("http://www.chabeichong.com/images/2014/07/11-2347573.jpg", "cat3.jpg");

        //创建执行服务
        ExecutorService service= Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> f1= (Future<Boolean>) service.submit(t1);
        Future<Boolean> f2= (Future<Boolean>) service.submit(t2);
        Future<Boolean> f3= (Future<Boolean>) service.submit(t3);

        //获取结果
        Boolean b1 = f1.get();
        Boolean b2 = f2.get();
        Boolean b3 = f3.get();

        //关闭服务
        service.shutdown();
    }
}

//下载器
class WebDownLoader{
    //下载方法
    public void downLoader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件io异常");
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值