java线程创建
一、线程创建
1.三种创建方式
- Thread类
- Runnable接口
- Callable接口
2.使用继承Thread类创建多线程
- 
自定义类继承Thread类 
- 
重写run方法 
- 
调用start开启线程 
- 
//Thread类线程测试 //1.创建自定义类继承Thread //2.重写run方法 //3.启动线程start //线程启动后并不一定立即执行,需要cpu调度 public class TestThread1 extends Thread{ //重写run方法 @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println("我不是主线程"+i); System.out.println(this.getId()); System.out.println(this.getState()); } } public static void main(String[] args) { TestThread1 testThread1 = new TestThread1(); testThread1.start(); for (int i = 0; i < 20; i++) { System.out.println("我是主线程"+i); } } }
- 
实例,用多线程实现网图的同时下载 ,使用commons.io包 import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; //多线程实例,使用多线程同时下载多个网络图片 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() { DownLoad downLoad = new DownLoad(); downLoad.downLoad(url,name); System.out.println(name+"下载成功"); } public static void main(String[] args) { TestThread2 t1 = new TestThread2("https://gitee.com/songping5201314/cloud-images/raw/master/img/image-20211120221646555.png","1.png"); TestThread2 t2 = new TestThread2("https://gitee.com/songping5201314/cloud-images/raw/master/img/20200511193414_jyirh.jpg","src/2.jpg"); TestThread2 t3 = new TestThread2("https://gitee.com/songping5201314/cloud-images/raw/master/img/image-20211208131014632.png ","src/3.jpg"); t1.start(); t2.start(); t3.start(); } } class DownLoad{ public void downLoad(String url,String name){ try { //默认的目录为项目的根目录 FileUtils.copyURLToFile(new URL(url),new File(name)); } catch (IOException e) { e.printStackTrace(); System.out.println("downLoad方法有错误"); } } }

3.使用实现Runnable接口的方式实现多线程
//推荐使用这种方式创建多线程,因为一个实现了Runnable接口的对象可以同时被多个Thread线程使用,避免了单继承的局限性
public class TestThread3 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("我不是主线程"+i);
        }
    }
    public static void main(String[] args) {
        TestThread3 testThread3 = new TestThread3();
        Thread thread=new Thread(testThread3);
        thread.start();//开启一个线程
        for (int i = 0; i < 100; i++) {
            System.out.println("我是主线程"+i);
        }
    }
}
4.线程的并发问题(不同步)
//多个线程同时对一个对象进行操作,产生资源的争夺,导致线程不安全
//模拟买票
public class TestThread4 implements Runnable{
    private int ticketnum=10;
    @Override
    public void run() {
        while(true){
            if (ticketnum==0){
                break;
            }
            try {
                Thread.sleep(200);//线程休眠0.2s
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"买了第"+ticketnum--+"张票");//会出现数据的混乱,线程不安全,不同步 
        }
    }
    public static void main(String[] args) {
        TestThread4 testThread4 = new TestThread4();
        new Thread(testThread4,"刘备").start();
        new Thread(testThread4,"张飞").start();
        new Thread(testThread4,"关羽").start();
    }
}

5.模拟龟兔赛跑
//模拟龟兔赛跑
public class Race implements Runnable{
    //定义一个胜利者
    private String winner;
    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            //模拟兔子休眠,第49步停一次
            if (Thread.currentThread().getName().equals("兔子") && i==50){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            boolean flag=gameOver(i);
            if (flag){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
        }
    }
    public boolean gameOver(int i){
        if (winner!=null){
            return true;
        }
        if (i>=100){
            winner=Thread.currentThread().getName();
            System.out.println("winner is"+Thread.currentThread().getName());
            return true;
        }
        return false;
    }
    public static void main(String[] args) {
        Race race=new Race();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}
6.通过Callable接口实现多线程
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务:ExecutorServer ser=Executors.newFixedThreadPool(x);
- 提交执行:Futureresult1=ser.submit(t1); 
- 获取结果:boolean r1=result1.get();//抛出异常
- 关闭服务:ser.shutdownNow();
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//通过实现callable接口实现多线程下载网络图片
public class CallableTest implements Callable<Boolean> {
    @Override
    public Boolean call() throws Exception {
        DownLoad downLoad = new DownLoad();
        downLoad.downLoad(url,name);
        System.out.println(name+"下载成功");
        return true;
    }
    private String url;
    private String name;
    public CallableTest(String url, String name) {
        this.url = url;
        this.name = name;
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CallableTest t1 = new CallableTest("https://gitee.com/songping5201314/cloud-images/raw/master/img/image-20211120221646555.png","1.png");
        CallableTest t2 = new CallableTest("https://gitee.com/songping5201314/cloud-images/raw/master/img/20200511193414_jyirh.jpg","src/2.jpg");
        CallableTest t3 = new CallableTest("https://gitee.com/songping5201314/cloud-images/raw/master/img/image-20211208131014632.png ","src/3.jpg");
        //创建执行服务:
        ExecutorService ser= Executors.newFixedThreadPool(3);
         //提交执行:
        Future<Boolean> result1=ser.submit(t1);
        Future<Boolean> result2=ser.submit(t2);
        Future<Boolean> result3=ser.submit(t3);
         //获取结果:
        boolean r1=result1.get();//抛出异常
        boolean r2=result2.get();//抛出异常
        boolean r3=result3.get();//抛出异常
        // 关闭服务:
        ser.shutdownNow();
    }
}
class DownLoader{
    public void downLoad(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("downLoad方法有错误");
        }
    }
}
本文来自博客园,作者:一只快乐的小67,转载请注明原文链接:https://www.cnblogs.com/sp520/p/16212258.html
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号