Java多线程

实现Runable

public class MyRunable implements Runnable {

    String str;

    public MyRunable(String str) {
        this.str = str;
    }

    @Override
    public void run() {
        for(int i = 1; i <= 10; i++) {
            System.out.println(str+"   "+i);
        }
    }
}

继承Thread

public class MyThread extends Thread{

    String str;

    public MyThread(String str) {
        this.str = str;
    }

    @Override
    public void run() {
        for(int i = 1; i <= 10; i++) {
            System.out.println(str+"   "+i);
        }
    }
}

测试代码

import org.junit.jupiter.api.Test;

public class ThreadTest {

    /**
     * 继承Thread实现多线程
     */
    @Test
    public void testThread(){
        MyThread myThread1=new MyThread("myThread1");
        MyThread myThread2=new MyThread("myThread2");
        myThread1.start();
        myThread2.start();
    }

    /**
     * 实现Runable接口实现多线程
     */
    @Test
    public void testRunable(){
        MyRunable myRunable1=new MyRunable("myRunable1");
        MyRunable myRunable2=new MyRunable("myRunable2");
        Thread thread1=new Thread(myRunable1);
        Thread thread2=new Thread(myRunable2);
        thread1.start();
        thread2.start();
    }

}

class MyRunnable implements Runnable {

    private volatile int ticketNum = 10;

    @Override
    public void run() {
        while (true) {
            if (ticketNum > 0) {
                System.out.println(Thread.currentThread().getName() + "抢到了第" + ticketNum-- + "张票");
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            else {
                break;
            }
        }
    }
}


public class Ticket {

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable();

        new Thread(myRunnable, "用户1").start();
        new Thread(myRunnable, "用户2").start();
        new Thread(myRunnable, "用户3").start();
    }

}

在这里插入图片描述
可以看到虽然用了volatile关键字,但volatile只保证可见性。在用户3抢到第5张票时,用户2抢到了票(第一步),将票的数量减1(第二步),用户1在用户2执行第一步完成后未开始第二步时,抢到了票,这时票的数量还未减1。

volatile使用场景

class Race implements Runnable {

    // 代表到达终点
    private volatile boolean flag = false;

    @Override
    public void run() {
        for (int i = 1; i<= 100; i++) {
            if (flag) {
                System.out.println(Thread.currentThread().getName() + "跑到了第" + i  + "步,失败");
                break;
            }
            else {
                System.out.println(Thread.currentThread().getName() + "第" + i + "步");
                if (i == 100) {
                    System.out.println(Thread.currentThread().getName() + "到达终点,胜利");
                    flag = true;
                }
            }
        }
    }
}

public class JavaTest {

    public static void main(String[] args) {

        Race race = new Race();
        new Thread(race, "xx").start();
        new Thread(race, "yy").start();
    }

}

Callable
参考链接:https://www.cnblogs.com/dolphin0520/p/3949310.html

import java.util.concurrent.*;

class MyCallable implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread() + "启动");
        int sum = 0;
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread() + "-" + i);
            sum += i;
        }
        return sum;
    }
}

public class JavaTest {

    public static void main(String[] args) {

        ExecutorService executor = Executors.newCachedThreadPool();
        Future<Integer> submit = executor.submit(new MyCallable());
        Future<Integer> submit2 = executor.submit(new MyCallable());
        try {
            System.out.println("submit结果" + submit.get());
            System.out.println("submit2结果" + submit2.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        executor.shutdown();
    }

}

输出:

Thread[pool-1-thread-2,5,main]启动
Thread[pool-1-thread-1,5,main]启动
Thread[pool-1-thread-2,5,main]-0
Thread[pool-1-thread-1,5,main]-0
Thread[pool-1-thread-1,5,main]-1
Thread[pool-1-thread-1,5,main]-2
Thread[pool-1-thread-1,5,main]-3
Thread[pool-1-thread-1,5,main]-4
Thread[pool-1-thread-2,5,main]-1
Thread[pool-1-thread-2,5,main]-2
Thread[pool-1-thread-2,5,main]-3
Thread[pool-1-thread-2,5,main]-4
submit结果10
submit2结果10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值