栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Java

Java(X):线程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java(X):线程

Runnable方法实现线程
  1. 实现Runnable接口
  2. 重写run方法,在run方法写逻辑
  3. 实例化写好的类,作为参数传入Thread方法(可以添加名字)
  4. 使用start方法开启线程,可以实现同一个对象被多个线程使用
静态代理(start是run的代理)
    private Marry target;//定义一个接口target
    
    public Company(Marry target){//构造器
        this.target = target;
    }

    @Override
    public void HappyMarry() {//重写方法,可以加入更多的东西
        before();
        this.target.HappyMarry();
        after();
    }
线程停止(建议使用flag标志)

在主线程中改变flag的值

package com.kafen.demo3;

import com.kafen.demo2.TestThread4;

// do not use while(1)
// use flag
// do not use stop or destroy
public class TestStop implements Runnable {
    private  boolean flag =true;
    @Override
    public void run() {
        int i =0;
        while(flag){
            System.out.println("runing..."+i++);
        }
    }

    public void stop(){
        this.flag=false;
    }

    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("main"+i);
            if(i==900){
                testStop.stop();
                System.out.println("Its time to stop");
            }

        }
    }
}


线程休眠(sleep) 使用线程下载图片
package com.kafen.demo1;

import org.apache.commons.io.FileUtils;

import javax.swing.*;
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() {
       WebDownloader webDownloader = new WebDownloader();
       webDownloader.downloader(url,name);
        System.out.println("Download File "+name);

    }

    public static void main(String[] args) {
        TestThread2 testThread1 = new TestThread2("https://img-blog.csdnimg.cn/20210418145852537.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA3ODcwNg==,size_16,color_FFFFFF,t_70","1.jpg");
        TestThread2 testThread2 = new TestThread2("https://img-blog.csdnimg.cn/20210418145852537.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA3ODcwNg==,size_16,color_FFFFFF,t_70","2.jpg");
        TestThread2 testThread3 = new TestThread2("https://img-blog.csdnimg.cn/20210418145852537.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NTA3ODcwNg==,size_16,color_FFFFFF,t_70","3.jpg");

        testThread1.start();
        testThread2.start();
        testThread3.start();
    }
}

class  WebDownloader{
    public void downloader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
# 并发


```java
package com.kafen.demo2;

public class TestThread4 implements Runnable{
    private int tickNums = 10;

    @Override
    public void run() {
        while(true){
            if(tickNums<=0){
                break;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName()+ " get "+tickNums--);

        }
    }

    public static void main(String[] args) {
        TestThread4 t4 = new TestThread4();
        new Thread(t4,"kafen").start();
        new Thread(t4,"jam").start();
        new Thread(t4,"lisa").start();


    }
}

龟兔赛跑
package com.kafen.demo2;

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("rabbit")&& i%10==0){
                try {
                    Thread.sleep(2);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            boolean flag = gameOver(i);
            if (flag){
                break;
            }
            System.out.println(Thread.currentThread().getName()+" run "+i +"step");

        }
    }

    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,"rabbit").start();
        new Thread(race,"turtle").start();
    }
}

线程停止



建议使用一个标志位让线程停止下来

线程礼让(礼让不一定成功)
package com.kafen.demo3;

public class TestYield {
    public static void main(String[] args) {
        MyYield myYield = new MyYield();
        new Thread(myYield,"a ").start();
        new Thread(myYield,"b ").start();
    }
}

class MyYield implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"thread start!");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"thread stop");
    }
}
线程插队
package com.kafen.demo3;

public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("this is vip"+i);
        }
    }

    public static void main(String[] args) {
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();

        for (int i = 0; i < 1000; i++) {
            if(i==200){
                try {
                    thread.join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("main"+i);

        }
    }
}

线程状态
package com.kafen.demo4;

public class TestState {
    public static void main(String[] args) {
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("/");
        });

        Thread.State state = thread.getState();
        System.out.println(state);

        thread.start();
        state = thread.getState();
        System.out.println(state);

        while (state!=Thread.State.TERMINATED){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            state= thread.getState();
            System.out.println(state);

        }
    }
}

优先级
package com.kafen.demo4;

public class TestPriority {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
        MyPriority myPriority = new MyPriority();
        Thread t1 = new Thread(myPriority);
        Thread t2 = new Thread(myPriority);
        Thread t3 = new Thread(myPriority);
        Thread t4 = new Thread(myPriority);
        Thread t5 = new Thread(myPriority);
        Thread t6 = new Thread(myPriority);

        t1.start();

        t2.setPriority(1);
        t2.start();

        t3.setPriority(4);
        t3.start();

        t4.setPriority(Thread.MAX_PRIORITY);
        t4.start();




    }
}

class MyPriority implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

守护线程
package com.kafen.demo4;

public class TestDeamon {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();

        Thread thread = new Thread(god);
        thread.setDaemon(true);
        thread.start();

        new Thread(you).start();
    }
}

class God implements Runnable{
    @Override
    public void run() {
        while(true){
            System.out.println("God bless you");
        }
    }
}

class You implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("living");
        }
        System.out.println("goodbye");
    }
}

线程同步(队列+锁)

(P20没有看)

转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/937784.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号