首页 > 编程语言 >java多线性--线程创建

java多线性--线程创建

时间:2022-09-30 19:56:51浏览次数:80  
标签:java String Thread -- 线程 new com public

java多线性--线程创建

什么是多线程:不同的功能同时进行

Process(进程)与Thread(线程)

  • 进程是执行程序的一次执行过程,是一个动态的概念。是系统分配资源的单位。
  • 一个进程分为多个线程,一个进程中至少包含一个线程。线程是CPU调度和执行的单位。

线程创建

创建线程的三种方式:

  • Thread:继承 Thread类
  • Runnable:实现Runnable接口
  • Callable:实现Callable接口 (了解)

Thread

  1. 自定义线程类继承Thread类。

  2. 重写其中的run()方法,编写线程执行体。

  3. 创建线程对象,调用start()方法启动线程。

package com.ssl.demo01;

//创建线程方式1:继承Thread类,重写run方法,调用start()方法
//总结:线程开启不一定立即执行,由CPU调度执行。

public class TestThread1 extends Thread{

    //重写run方法
    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 20; i++) {
            System.out.println("我在看代码--"+i);
        }
    }

    public static void main(String[] args) {
        //创建线程对象,调用start方法
        TestThread1 testThread1 = new TestThread1();
        testThread1.start();    //交替执行
        //testThread1.run();    先执行完,再走主线程。

        //main线程 主线程
        for (int i = 0; i < 20; i++) {
            System.out.println("我在学习多线程---"+i);
        }
    }

}

练习下载图片

apache下载:

http://commons.apache.org/proper/commons-io/

package com.ssl.demo01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.lang.String;

//练习Thread,实现多线程同步下载图片
public class TestThread2 extends Thread{

    private String url;
    private String name;

    //构造器
    public TestThread2(String url, String name){
        this.url = url;
        this.name = name;
    }



    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为:"+name);
    }

    public static void main(String[] args) {
        TestThread2 test1 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwx3.sinaimg.cn%2Fmw690%2F006a7Fqsly1h6l1m1o2v8j31o02yo7wi.jpg&refer=http%3A%2F%2Fwx3.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102238&t=2663277ec5f007ad772e6cface75ec86","1.png");
        TestThread2 test2 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbkimg.cdn.bcebos.com%2Fpic%2F37d12f2eb9389b504fc209f70a7af2dde71190efc04c&refer=http%3A%2F%2Fbkimg.cdn.bcebos.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102500&t=ce4bf55425348082daa6f6e5132a8920","2.png");
        TestThread2 test3 = new TestThread2("https://img1.baidu.com/it/u=4282593950,4216695015&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=515","3.png");
        TestThread2 test4 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F11324654676%2F1000.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102566&t=e9f6e5a7c126a283489789301cacb584","4.png");

        test1.start();
        test2.start();
        test3.start();
        test4.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异常,downloader方法出问题");
        }
    }
}

Runnable

步骤:

  1. 定义MyRunable类实现Runable接口
  2. 实现run()方法
  3. 创建线程对象,调用start()方法启动线程
package com.ssl.demo01;


//创建线程方法2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法。
public class TestThread3 implements Runnable{

    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 20; i++) {
            System.out.println("我在看代码--"+i);
        }
    }

    public static void main(String[] args) {
        //创建线程对象
        TestThread3 testThread3 = new TestThread3();
        //创建一个Thread;  把实现对象丢进去。
        Thread thread = new Thread(testThread3);
        thread.start();

        //main线程 主线程
        for (int i = 0; i < 20; i++) {
            System.out.println("我在学习多线程--"+i);
        }
    }
}

练习:

package com.ssl.demo01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class TestThread4 implements Runnable{

    private String url;
    private String name;

    //构造器
    public TestThread4(String url, String name){
        this.url = url;
        this.name = name;
    }



    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为:"+name);
    }

    public static void main(String[] args) {
        TestThread4 test1 = new TestThread4("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwx3.sinaimg.cn%2Fmw690%2F006a7Fqsly1h6l1m1o2v8j31o02yo7wi.jpg&refer=http%3A%2F%2Fwx3.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102238&t=2663277ec5f007ad772e6cface75ec86","1.png");
        TestThread4 test2 = new TestThread4("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbkimg.cdn.bcebos.com%2Fpic%2F37d12f2eb9389b504fc209f70a7af2dde71190efc04c&refer=http%3A%2F%2Fbkimg.cdn.bcebos.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102500&t=ce4bf55425348082daa6f6e5132a8920","2.png");
        TestThread4 test3 = new TestThread4("https://img1.baidu.com/it/u=4282593950,4216695015&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=515","3.png");
        TestThread4 test4 = new TestThread4("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F11324654676%2F1000.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102566&t=e9f6e5a7c126a283489789301cacb584","4.png");

        Thread t1 = new Thread(test1);
        Thread t2 = new Thread(test2);
        Thread t3 = new Thread(test3);
        Thread t4 = new Thread(test4);

        t1.start();
        t2.start();
        t3.start();
        t4.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异常,downloader方法出问题");
        }
    }
}

推荐使用Runnable实现方式。

多线程同时操作一个方法

并发问题: 多个线程操作一个对象时,会产生并发问题。

package com.ssl.demo01;

//多线程同时操作一个对象
//买火车票的例子
public class TestThread5 implements Runnable{

    //票数
    private int ticketNums = 10;

    @Override
    public void run() {
        while (true) {
            if(ticketNums==0)
                break;
            //模拟延时,会存在并发问题
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //得到当前线程的名字
            System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"票");
        }
    }

    public static void main(String[] args) {
        TestThread5 tickle = new TestThread5();


        Thread thread1 = new Thread(tickle,"小明");
        Thread thread2 = new Thread(tickle,"大黄");
        Thread thread3 = new Thread(tickle,"老师");
        Thread thread4 = new Thread(tickle,"黄牛党");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }


}

龟兔赛跑

package com.ssl.demo01;

public class Race implements Runnable{

    //胜利者
    private static String winner;

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            //判断比赛是否结束
            boolean flag = gameOver(i);
            if(flag){
                break;
            }
            //模拟兔子睡觉
            if(Thread.currentThread().getName()=="兔子" && (i+1)%50==0) {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
        }
    }

    //判断是否完成比赛
    private boolean gameOver(int steps){
        if(winner!=null){
            return true;
        }else{
            if (steps >= 99){
                winner = Thread.currentThread().getName();
                System.out.println("胜利者"+winner);
                return true;
            }
            return false;
        }

    }
    public static void main(String[] args) {
        Race race = new Race();

        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();

    }
}

Callable

步骤:(了解即可)

  1. 实现Callable接口,需要返回值类型
  2. 重写call方法,需要抛出异常
  3. 创建目标对象
  4. 创建执行服务:
ExecutoService ser = Exectors.newFixedThreadPool(数量);
  1. 提交执行:
Future<Boolean> result1 = ser.submit(t1);
  1. 获取结果
boolean r1 = result1.get();
  1. 关闭服务
ser.shutdownNow();

实现下载图片

package com.ssl.demo01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//线程创建方法3 实现callable接口
/**
 *
 */

public class TestCallable implements Callable<Boolean> {

    private String url;
    private String name;

    @Override
    public Boolean call(){
        WebDownloader2 webDownloader = new WebDownloader2();
        webDownloader.downloader(url,name);
        System.out.println("下载了文件名为:"+name);
        return true;
    }

    //构造器
    public TestCallable(String url, String name){
        this.url = url;
        this.name = name;
    }



    public static void main(String[] args) {
        TestCallable test1 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwx3.sinaimg.cn%2Fmw690%2F006a7Fqsly1h6l1m1o2v8j31o02yo7wi.jpg&refer=http%3A%2F%2Fwx3.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102238&t=2663277ec5f007ad772e6cface75ec86","1.png");
        TestCallable test2 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbkimg.cdn.bcebos.com%2Fpic%2F37d12f2eb9389b504fc209f70a7af2dde71190efc04c&refer=http%3A%2F%2Fbkimg.cdn.bcebos.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102500&t=ce4bf55425348082daa6f6e5132a8920","2.png");
        TestCallable test3 = new TestCallable("https://img1.baidu.com/it/u=4282593950,4216695015&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=515","3.png");
        TestCallable test4 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F11324654676%2F1000.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102566&t=e9f6e5a7c126a283489789301cacb584","4.png");

        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(4);

        //提交执行
        Future<Boolean> result1 = ser.submit(test1);
        Future<Boolean> result2 = ser.submit(test2);
        Future<Boolean> result3 = ser.submit(test3);
        Future<Boolean> result4 = ser.submit(test4);


        //获取结果
        try {
            boolean rs1 = result1.get();
            boolean rs2 = result2.get();
            boolean rs3 = result3.get();
            boolean rs4 = result4.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }

        //关闭服务
        ser.shutdownNow();
    }
}


//下载器
class WebDownloader2{
    //下载方法
    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异常,downloader方法出问题");
        }
    }
}

标签:java,String,Thread,--,线程,new,com,public
From: https://www.cnblogs.com/ssl-study/p/16745944.html

相关文章

  • 继承
    继承继承的本质是对某一批类的抽象,从而实现对现实世界更好的建模extends的意思是“扩展”。子类是父类的扩展JAVA中类只有单继承,没有多继承!继承是类和类之间的一种关......
  • 25.防止空指针调用成员函数
    程序1:#pragmawarning(disable:4996)#include<iostream>usingnamespacestd;classMaker{public:Maker(){a=20;}voidprint......
  • Raft 共识算法
    转载请注明出处:https://www.cnblogs.com/morningli/p/16745294.htmlraft是一种管理复制日志的算法,raft可以分解成三个相对独立的子问题:选主(Leaderelection):原有的lead......
  • AutoHotKet相关
    :win键!:alt^:ctrl:shift符号::意味着每次按下前面的热键时,随后的命令将会被执行。Run命令:用来启动一个程序、文档、URL网址或者快捷方式。如:;分号表示注释^q......
  • vue element-ui 基本使用和按需加载的2种方式(推荐安装插件的方式)
    element-ui官网:https://element.eleme.cn/#/zh-CN/component/installation 安装npminstallelement-ui-S不太清楚这里为什么是-S的朋友可以看看我的这篇文章......
  • Android Studio运行Failed to find Build Tools revision 30.0.3
    问题第一次安装好AndroidStudio2022.5的版本之后开启虚拟机运行文件报错提示FailedtofindBuildToolsrevision30.0.3打开SDK已经安装了33.0.0,报错提示找不到30.......
  • 实验2:Open vSwitch虚拟交换机实践
    实验2:OpenvSwitch虚拟交换机实践一、实验目的能够对OpenvSwitch进行基本操作;能够通过命令行终端使用OVS命令操作OpenvSwitch交换机,管理流表;能够通过Mininet的Pytho......
  • 代码大全1第二篇阅读笔记
    第二章:用隐喻更充分的理解软件开发1、当将软件的构建过程比作房屋的构建过程时,可以发现,仔细的准备是必要的,发生变动时最贵的成本是人的时间,而大型项目和小型项目之间也有差......
  • java字符串输入然后语音输出
    1.将jacob.jar考到项目中进行构建路径。2.将jacob-1.17-M2-x32.dll或者jacob-1.17-M2-x64.dll,考到系统盘:\Windows\System32\下面。3.将jacob-1.17-M2-x32.dll或者jacob-......
  • 内置方法字符编码讲解
    字典相关操作​类型转换$$dict()$$字典的转换一般不使用关键字而是自己动手转​字典必须要掌握的操作$$user_dict={'username':'jason','password':123,'......