创建线程方式一:继承Thread

1、同时执行,cpu决定交替执行

  1. //创建线程方式一:继承Thread类,重写run方法,调用start开启线程
  2. public class TestThread1 extends Thread{
  3. @Override
  4. public void run() {
  5. //run方法线程体
  6. for (int i = 0; i <200 ; i++) {
  7. System.out.println("我在学习java呢!"+i);
  8. }
  9. }
  10. public static void main(String[] args) {
  11. //main线程主线程
  12. //创建一个线程对象
  13. TestThread1 testThread1 = new TestThread1();
  14. //调用start()方法开启线程
  15. testThread1.start();
  16. for (int i = 0; i <1000 ; i++) {
  17. System.out.println("我在看p站呢哈哈哈哈哈"+i);
  18. }
  19. }
  20. }

2、练习Thread,实现多线程同步下载图片

  1. //练习Thread,实现多线程同步下载图片
  2. public class TestThread2 extends Thread{
  3. private String url;
  4. private String name;
  5. public TestThread2(String url,String name){
  6. this.url=url;
  7. this.name=name;
  8. }
  9. @Override
  10. public void run() {
  11. WebDownLoader webDownLoader = new WebDownLoader();
  12. webDownLoader.downloader(url,name);
  13. System.out.println("下载的文件名:"+name);
  14. }
  15. public static void main(String[] args) {
  16. TestThread2 t1 = new TestThread2("http://www.zto56.com/images/page/recruit-xuanjiang.png", "1.jpg");
  17. TestThread2 t2 = new TestThread2("http://www.zto56.com/images/page/recruit-xuanjiang.png", "2.jpg");
  18. TestThread2 t3= new TestThread2("http://www.zto56.com/images/page/recruit-xuanjiang.png", "3.jpg");
  19. t1.start();
  20. t2.start();
  21. t3.start();
  22. }
  23. }
  24. //下载器
  25. class WebDownLoader{
  26. //下载方法
  27. public void downloader(String url,String name){
  28. try {
  29. //将url链接变成一个文件
  30. FileUtils.copyURLToFile(new URL(url),new File(name));
  31. } catch (IOException e) {
  32. e.printStackTrace();
  33. System.out.println("IO异常,downloader方法出现问题!");
  34. }
  35. }
  36. }

创建线程方式二:实现Runnable接口:

  1. //创建线程方式2:实现Runnable接口,重写run方法,执行线程需要丢入Thread中
  2. public class TestThread3 implements Runnable{
  3. @Override
  4. public void run() {
  5. for (int i = 0; i <200 ; i++) {
  6. System.out.println("我在学习java呢"+i);
  7. }
  8. }
  9. public static void main(String[] args) {
  10. TestThread3 t1 = new TestThread3();
  11. //执行线程
  12. new Thread(t1).start();
  13. for (int i = 0; i <1000 ; i++) {
  14. System.out.println("我在看bilibili呢"+i);
  15. }
  16. }
  17. }

总结:

继承Thread类:

子类继承Thread类具备多线程能力

启动线程:子类对象.start()

不建议使用:避免OOP单继承的局限性

实现Runnable接口:

实现接口Runnble具备多线程的能力

启动线程:传入目标对象+Thread对象.start()

推荐使用:避免了单继承的局限性,灵活方便,方便同一个对象多个线程使用
初始并发问题:

  1. //多个线程同时操作同一个对象
  2. //抢火车票的例子
  3. public class TestThread4 implements Runnable{
  4. //票数
  5. private int ticketNums=10;
  6. @Override
  7. public void run() {
  8. while (true){
  9. if (ticketNums<=0){
  10. break;
  11. }
  12. //模拟演示
  13. try {
  14. Thread.sleep(200);
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票。");
  19. }
  20. }
  21. public static void main(String[] args) {
  22. TestThread4 t1=new TestThread4();
  23. new Thread(t1,"小明").start();
  24. new Thread(t1,"小红").start();
  25. new Thread(t1,"小龙").start();
  26. new Thread(t1,"黄牛").start();
  27. }
  28. }

发现问题:多个线程操作同一个对象下,线程不安全,数据紊乱数据被破坏!

2.创建多线程的方式 - 图1

模拟龟兔赛跑:兔子走十步就停下休息,乌龟不休息

胜利者乌龟!

//模拟龟兔赛跑
public class Race implements Runnable{
private static String winner;//胜利者


@Override
public void run() {
    for (int i = 0; i <= 100; i++) {
        //模拟兔子休息
        if (Thread.currentThread().getName().equals("兔子")&&i%10==0){

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //判断比赛是否结束
        boolean flag=gameOver(i);
        if (flag){
            break;
        }

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

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

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

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

创建线程方式三:实现Callable接口:

public class TestCallable implements Callable {
private  String name;
private String url;
public TestCallable(String name ,String url){
    this.name=name;
    this.url=url;
}

@Override
public Boolean call() {
    WebDownLoader webDownLoader = new WebDownLoader();
    webDownLoader.downloader(url,name);

    System.out.println("文件下载中"+name);
    return true;
}

public static void main(String[] args) throws ExecutionException, InterruptedException {
    TestThread2 t1 = new TestThread2("7.jpg", "http://www.zto56.com/images/page/recruit-xuanjiang.png");
    TestThread2 t2 = new TestThread2("8.jpg", "http://www.zto56.com/images/page/recruit-xuanjiang.png");
    TestThread2 t3 = new TestThread2("9.jpg", "http://www.zto56.com/images/page/recruit-xuanjiang.png");


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

    //执行代码
    Future<Boolean> r1 = (Future<Boolean>) ser.submit(t1);
    Future<Boolean> r2 = (Future<Boolean>) ser.submit(t2);
    Future<Boolean> r3 = (Future<Boolean>) ser.submit(t3);

    //获取结果
    Boolean rs1 = r1.get();
    Boolean rs2 = r2.get();
    Boolean rs3 = r3.get();

    //关闭服务
    ser.shutdown();


}
}
//下载器
class WebDownLoader1{
//下载方法
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出错了!");
    }
}
    }