多线程

本文介绍了Java中线程的多种实现方式,包括通过继承Thread类、实现Runnable接口及使用Callable与Future。此外,还详细讲解了如何利用ReentrantLock进行同步控制、使用ReadWriteLock实现读写分离以及通过Exchanger进行线程间数据交换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、线程的实现方式

     1.1、继承Thread类

public class ThreadImplementation extends Thread{
    
    @Override
    public void run() {
        System.out.println("线程实现方式之继承Thread类......" + Thread.currentThread().getName());
    }
    
    public static void main(String[] args) {
        new ThreadImplementation().start();
    }
    
}

  1.2、实现Runnable接口

public class RunnableImplementation implements Runnable{

    @Override
    public void run() {
        System.out.println("线程实现方式之实现Runnable接口......" + Thread.currentThread().getName());
    }
    
    public static void main(String[] args) {
        new Thread(new RunnableImplementation()).start();
    }
    
}

 1.3、有返回值的实现方式

public class CallableAndFutureTest {
    
    public static void main(String[] args) throws Throwable {
        Date start = new Date();
//        创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程。
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        List<Future> futures = new ArrayList<Future>();
        for(int i = 0; i < 3; i++){
            Callable callable = new MyCallable(i + "");
            Future future = executorService.submit(callable);
            futures.add(future);
        }
        executorService.shutdown();
        System.out.println("打印返回信息");
        for(Future future : futures){
            System.out.println(">>>" + future.get().toString());
        }
        Date end = new Date();
        System.out.println("耗时:" + (end.getTime() - start.getTime()));
    }
}

class MyCallable implements Callable<Object>{

    private String num;

    MyCallable(String num) {
        this.num = num;
    }
    
    @Override
    public Object call() throws Exception {
        System.out.println(">>>运行" + num +"任务开始");
        System.out.println("do something......" + num);
        System.out.println(">>>运行" + num +"任务结束");
        return num + "完成!";
    }
    
}

1.3.1、CallableAndFutureTest2

public class CallableAndFutureTest2 {
    
    public static void main(String[] args) throws Throwable{
        //返回一个线程池(这个线程池只有一个线程)
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<String> future = executorService.submit(new Callable<String>() {

            @Override
            public String call() throws Exception {
                return "Hello";
            }
        });

       executorService.shutdown();

        System.out.println(future.get());
    }
}

 1.3.2、CallableAndFutureTest3

public class CallableAndFutureTest3 {
    
    public static void main(String[] args) throws Throwable{
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(executorService);
        for(int i = 0; i < 3; i ++){
            final int seq = i;
            completionService.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return seq;
                }
            });
        }
        for(int i = 0; i < 3; i ++){
            System.out.println(completionService.take().get());
        }
    }
}

2、锁


public class LockTest {
    
    public static void main(String[] args) {
        new LockTest().init();
    }
    
    private void init() {
        final Outputer outputer = new Outputer();
        for (int i = 0; i < 30; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    outputer.output("AAAAA");
                }
            }).start();
        }
        
        for (int i = 0; i < 30; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    outputer.output("BBBBB");
                }
                
            }).start();
        }
    }
    
    static class Outputer {
        Lock lock = new ReentrantLock();
        
        public void output(String name) {
            int len = name.length();
            lock.lock();
            try {
                for (int i = 0; i < len; i++) {
                    System.out.print(name.charAt(i));
                }
                System.out.println();
            }
            finally {
                lock.unlock();
            }
        }
    }
    
}


public class ReadWriteLockTest {
    
    public static void main(String[] args) {
        final Queue queue = new Queue();
        //写数据
        new Thread(){
            @Override
            public void run() {
                queue.put(new Random().nextInt(10000));
            }
            
        }.start();
        //读数据
        new Thread(){
            @Override
            public void run() {
                queue.get();
            }
        }.start();
        
    }
    
}


class Queue{
    ////共享数据,只有一个线程能够写该数据,但是可以多个线程可以读该线程
    private Object data;
    //读写锁
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    //写数据
    public void put(Object data){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正准备写数据!");
            Thread.sleep((long)Math.random() * 1000);
            this.data = data;
            System.out.println(Thread.currentThread().getName() + "已经写完数据data:"  + data);
        }
        catch (InterruptedException e) {
        }finally{
            readWriteLock.writeLock().unlock();
        }
    }
    //读数据
    public void get(){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "正准备读取数据!");
            Thread.sleep((long)Math.random() * 1000);
            System.out.println(Thread.currentThread().getName() + "已经读取到数据data:"  + data);
        }
        catch (InterruptedException e) {
        }finally{
            readWriteLock.readLock().unlock();
        }
    }
}
3、数据交换

public class ExchangerTest {
    
    public static void main(String[] args) throws Throwable {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Exchanger exchanger = new Exchanger();
        
        executorService.execute(new Runnable() {
            
            @Override
            public void run() {
                try {
                    String sendData = "A发送的数据";
                    System.out.println("线程:" + Thread.currentThread().getName() + "正准备把数据\t" + sendData + "\t换出去");
                    Thread.sleep((long) Math.random() * 10000);
                    String returnData = (String) exchanger.exchange(sendData);
                    System.out.println("线程:" + Thread.currentThread().getName() + "\t换回的数据\t" + returnData);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        
        executorService.execute(new Runnable() {
            
            @Override
            public void run() {
                try {
                    String sendData = "B发送的数据";
                    System.out.println("线程:" + Thread.currentThread().getName() + "正准备把数据\t" + sendData + "\t换出去");
                    Thread.sleep((long) Math.random() * 10000);
                    String returnData = (String) exchanger.exchange(sendData);
                    System.out.println("线程:" + Thread.currentThread().getName() + "\t换回的数据\t" + returnData);
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            
        });
        
    }
    
}

4、定时器

     public class TimerTaskTest {
    
    private static int count = 0;
    
    public static void main(String[] args) {
        new Timer().schedule(new MyTimerTask(), 2000);
        while(true){
            System.out.println(new Date().getSeconds());
            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class MyTimerTask extends TimerTask{

        @Override
        public void run() {
                count = (count + 1) %2;
                System.out.println("爆炸......");
                new Timer().schedule(new MyTimerTask(), 2000 + 2000 * count);
        }
        
    }
    
}

public class TimerTaskTest2{
    
    public static void main(String[] args) {
        Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println("爆炸......");
            }
            
        }, 4, 2, TimeUnit.SECONDS);
        
        while (true) {
            System.out.println(new Date().getSeconds());
            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
    }
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值