Java 并发线程实例

实现方式

1. 继承 Thread
package thread;

public class ThreadService extends Thread{
    @Override
    public void run() {
        //RUN
        for (int i=0;i<200;i++){
            System.out.println("线程=============="+i);
        }
    }

    public static void main(String[] args) {
        ThreadService threadService=new ThreadService();
        ThreadService threadService2=new ThreadService();
//        threadService.run();
        threadService.start();//开启线程
        threadService2.start();//开启线程
        for (int i=0;i<2000;i++){
            System.out.println("线程="+i);
        }
    }
}

2.实现 Runnable 接口
package thread;

public class TestThread implements Runnable{

    public void run() {
        for (int i=0;i<200;i++){
            System.out.println("run...."+i);
        }
    }

    public static void main(String[] args) {
        TestThread testThread = new TestThread();
        new Thread(testThread).start();

        for (int i=0;i<200;i++){
            System.out.println("main...."+i);
        }
    }
}

3.实现 Callable 接口
package thread;

import java.util.concurrent.*;

public class TestCallable implements Callable<Boolean> {

    private String name;

    public TestCallable(String name) {
        this.name = name;
    }

    public Boolean call() throws Exception {
        System.out.println("->"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        TestCallable testThread1 = new TestCallable("1号");
        TestCallable testThread2 = new TestCallable("2号");
        TestCallable testThread3 = new TestCallable("3号");
        //创建执行任务
        ExecutorService ex=Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> r1=ex.submit(testThread1);
        Future<Boolean> r2=ex.submit(testThread2);
        Future<Boolean> r3=ex.submit(testThread3);

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

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

线程特性相关

1.线程生命周期
package thread;

public class TestState {

    public static void main(String[] args) {
        Thread thread = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(i);
            }

        });

        //线程状态 :NEW
        Thread.State state=thread.getState();
        System.out.println(state);

        //线程状态 :RUN
        thread.start();
        state=thread.getState();
        System.out.println(state);
        
        //等待线程
        while (state!=Thread.State.TERMINATED){
            state=thread.getState();
            System.out.println(state);
        }

        //结束
        state=thread.getState();
        System.out.println(state);

    }

}

2.线程礼让(不一定成功,具体还要看CPU的调度顺序)
package thread;
//礼让不一定成功
public class TestYield {
    private static MyYield  myYield=new MyYield();

    public static void main(String[] args) {
        new Thread(myYield,"A").start();
        new Thread(myYield,"B").start();
        new Thread(myYield,"C").start();
    }
}

class  MyYield implements Runnable{

    public void run() {
        System.out.println(Thread.currentThread().getName()+"开始--------");
        Thread.yield();//礼让
        System.out.println(Thread.currentThread().getName()+"结束--------");
    }
}
3.线程优先级(不一定成功,只是设置了,具体还要看CPU的调度顺序)
package thread;

public class TestPriority{

    public static void main(String[] args) {
        System.out.println("main->"+Thread.currentThread().getPriority());
        MyPriorty myPriorty = new MyPriorty();
        Thread thread1 = new Thread(myPriorty,"A");
        Thread thread2 = new Thread(myPriorty,"B");
        Thread thread3 = new Thread(myPriorty,"C");
        Thread thread4 = new Thread(myPriorty,"D");
        Thread thread5 = new Thread(myPriorty,"E");
        thread1.start();

        //设置优先级
        thread2.setPriority(3);
        thread2.start();

        thread3.setPriority(6);
        thread3.start();

        thread4.setPriority(10);
        thread4.start();

        thread5.setPriority(Thread.MAX_PRIORITY);//最大默认是 10 ,取值范围是 1-10
        thread5.start();

    }

}

class MyPriorty implements Runnable{

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

}
4.插队线程
package thread;

public class TestJoin implements Runnable{
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("VIP 线程="+i);
        }
    }

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

        //主线程
        for (int i = 0; i < 500; i++) {
            if(i==100){
                try {
                    thread.join();// 让他插队
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("主线程=="+i);
        }
    }
}

5.线程停止的推荐方式
package thread;

public class TestStop implements Runnable{

    private static boolean flag=true;

    public void run() {
        int i=0;
        while(flag){
            System.out.println("main->"+i++);
        }
    }

    public static void stop(){
            flag=false;
    }

    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();
        for (int i = 0; i < 10000000; i++) {
            if(i>=900000){
                testStop.stop();
                System.out.println("STOP!!!");
                break;
            }
        }
    }
}

6.线程不安全与安全线程的演示
package thread;

import java.util.ArrayList;

public class TestSysList {
    public static void main(String[] args) {

        ArrayList<Object> list = new ArrayList<>();
        ArrayList<Object> unList = new ArrayList<>();

        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                synchronized (list){
                    list.add(Thread.currentThread().getName());
                }
                unList.add(Thread.currentThread().getName());
            }).start();
        }
        //这里要保证异步线程执行完,所以需要睡眠一下!
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("加锁=="+list.size());
        System.out.println("未加锁=="+unList.size());

    }
}

7.守护线程
package thread;

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

        Thread threadYou = new Thread(you);
        Thread threadGod = new Thread(god);
        threadYou.start();
        threadGod.setDaemon(true);
        threadGod.start();
    }
}

//上帝(守护线程)
class God implements Runnable{

    @Override
    public void run() {
        while (true){
            System.out.println("守护....");
        }
    }
}

//人(默认线程)
class You implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("执行。。。。。"+i);
        }
    }
}
8.线程死锁与解锁

死锁线程:

package thread;
//死锁
public class TestDealLock {
    public static void main(String[] args) {
        Makeup makeup = new Makeup();
        new Thread(makeup,"A").start();
        new Thread(makeup,"B").start();
    }
}

//口红
class Lipstick{
}

//镜子
class Mirror{
}

class Makeup extends Thread{

    //口红
    static Lipstick lipstick=new Lipstick();
    //镜子
    static Mirror mirror=new Mirror();

    @Override
    public void run() {
        making();
    }

    //开始化妆
    public void making(){
        String name=Thread.currentThread().getName();
        if(name=="A"){
            synchronized (lipstick){
                System.out.println(name+"==拿到了口红!");

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (mirror){
                    System.out.println(name+"==拿到了镜子!");
                }
            }
        }else{
            synchronized (mirror){
                System.out.println(name+"==拿到了镜子!");

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lipstick){
                    System.out.println(name+"==拿到了口红!");
                }
            }
        }

    }
}

解锁:

package thread;
//死锁
public class TestDealLock {
    public static void main(String[] args) {
        Makeup makeup = new Makeup();
        new Thread(makeup,"A").start();
        new Thread(makeup,"B").start();
    }
}

//口红
class Lipstick{
}

//镜子
class Mirror{
}

class Makeup extends Thread{

    //口红
    static Lipstick lipstick=new Lipstick();
    //镜子
    static Mirror mirror=new Mirror();

    @Override
    public void run() {
        making();
    }

    //开始化妆
    public void making(){
        String name=Thread.currentThread().getName();
        if(name=="A"){
            synchronized (lipstick){
                System.out.println(name+"==拿到了口红!");

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
               
            }
            //解锁
             synchronized (mirror){
                    System.out.println(name+"==拿到了镜子!");
            }
        }else{
            synchronized (mirror){
                System.out.println(name+"==拿到了镜子!");

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
               
            }
            //解锁
             synchronized (lipstick){
                    System.out.println(name+"==拿到了口红!");
                }
        }

    }
}
9.JUC下的安全list
package thread;

import java.util.concurrent.CopyOnWriteArrayList;

public class TestJuc {

    public static void main(String[] args) {
        CopyOnWriteArrayList<Object> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }

        //睡眠一下,保证他执行完
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(list.size());

    }

}

线程池详解

请参考此文:https://www.freesion.com/article/42591110359/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会飞的小蜗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值