线程

线程第一种定义方式:

1.继承Thread类   2.在子类中重写run()方法    3.调用start()方法启动线程(自带方法不是定义方法)

public class Test {
class Runner extends Thread{
@Override
public void run() {
Integer speed = new Random().nextInt(10);
for (int i = 1; i <= 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("第"+i+"秒"+this.getName()+"已跑到"+(i*speed)+"米,速度"+speed);
}

}
}
public void start(){
Runner runner = new Runner();
Thread thread = new Thread(runner);
thread.start();
}

public static void main(String[] args) {
new Test().start();
}

}

线程第二种定义方式:

 通过Runnable接口实现   

public class Test {
    class Runner implements Runnable{

        @Override
        public void run() {
            Integer speed = new Random().nextInt(10);
            for (int i = 1; i <= 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("第"+i+"秒"+Thread.currentThread().getName()+"已跑到"+(i*speed)+"米,速度"+speed);//与第一种实现方式相比,此处代码差别最大
            }

        }
    }
    public void start(){
        Runner runner = new Runner();
        Thread thread = new Thread(runner);
        thread.setName("参赛者A");
        thread.start();
    }

    public static void main(String[] args) {
        new Test().start();
    }

}

 线程第三种定义方式

import java.util.Random;
import java.util.concurrent.*;
//实现Callable接口实现多线程程序
public class ThreadSample3 {
class Runner implements Callable<Integer>{
public String name;
@Override
public Integer call() throws Exception {
Integer speed = new Random().nextInt(10);
Integer result = 0;
for(int i = 1 ; i <= 10 ; i++){
Thread.sleep(1000);
result = i * speed;
System.out.println("第" + i + "秒:" + this.name + "已跑到" + (i * speed) + "米(" + speed + "米/秒)");
}
return result;
}
}

public void start() throws ExecutionException, InterruptedException {
//创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(3);
Runner threadA = new Runner();
threadA.name = "参赛者A";
Runner threadB = new Runner();
threadB.name = "参赛者B";
Runner threadC = new Runner();
threadC.name = "参赛者C";
//利用Future对象获取每一个线程执行后的结果
Future<Integer> r1 = executorService.submit(threadA);
Future<Integer> r2 = executorService.submit(threadB);
Future<Integer> r3 = executorService.submit(threadC);
//关闭线程池
executorService.shutdown();
System.out.println(threadA.name + "累计跑了" + r1.get() + "米");
System.out.println(threadB.name + "累计跑了" + r2.get() + "米");
System.out.println(threadC.name + "累计跑了" + r3.get() + "米");
}

public static void main(String[] args) throws ExecutionException, InterruptedException {
new ThreadSample3().start();
}
}

 线程同步,设置锁的各种方式

public class SyncSample {

    class Printer{
        //锁对象
        Object lock = new Object();
        //synchronized代码块演示,对自定义对象lock上锁
        public void print1(){
            synchronized (lock) {
                try {
                    Thread.sleep(500);
                    System.out.print("魑");
                    Thread.sleep(500);
                    System.out.print("魅");
                    Thread.sleep(500);
                    System.out.print("魍");
                    Thread.sleep(500);
                    System.out.print("魉");
                    System.out.println();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        //synchronized方法 - 对this当前对象上锁
        public synchronized void print2(){
            try {
                //this
                Thread.sleep(500);
                System.out.print("魑");
                Thread.sleep(500);
                System.out.print("魅");
                Thread.sleep(500);
                System.out.print("魍");
                Thread.sleep(500);
                System.out.print("魉");
                System.out.println();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //synchronized静态方法 - 该类的字节码对象Printer.class
        /*
        public static synchronized void print3(){
            try {
                //Printer.class
                Thread.sleep(500);
                System.out.print("魑");
                Thread.sleep(500);
                System.out.print("魅");
                Thread.sleep(500);
                System.out.print("魍");
                Thread.sleep(500);
                System.out.print("魉");
                System.out.println();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        */
    }

    class PrintTask implements Runnable{
        public Printer printer;
        @Override
        public void run() {
            printer.print2();
        }
    }

    public void start(){
        Printer printer = new Printer();
        for(int i = 0 ; i < 10 ; i++){
            PrintTask task = new PrintTask();
            task.printer = printer;
            Thread thread = new Thread(task);
            thread.start();
        }
    }

    public static void main(String[] args) {
        SyncSample sample = new SyncSample();
        sample.start();
    }
}

线程安全问题以及解决超卖现象

public class Stock {
    //当前商品库存剩余3个
    public static int count = 3;
}


class Consumer implements Runnable{
    //所有消费者都来到同一个商城
    public Mall mall;
    @Override
    public void run() {
        //商城为每一名消费者销售商品
        mall.sale();
    }
}


public class Mall {
    public synchronized void sale(){//通过在此添加synchronized的方式设置锁,否则商品库存数量会出现负数超卖
        if(Stock.count > 0 ){
            try {
                //模拟商城办理销售业务,用时5毫秒
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //销售成功库存减少
            Stock.count--;
            System.out.println("商品销售成功");
        }else{
            System.out.println("商品库存不足,请下次再来吧!");
        }
    }

    public static void main(String[] args) {
        //实例化唯一的商城对象
        Mall mall = new Mall();
        //模拟5名顾客同时涌入商城购买商品
        for(int i = 0 ; i < 100 ; i++){
            Consumer consumer = new Consumer();
            consumer.mall = mall;
            Thread thread = new Thread(consumer);
            thread.start();
        }
        try {
            //模拟下班后判断库存
            Thread.sleep(1000);
            System.out.println("当前商品库存为:" + Stock.count);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

在此处因为判定几乎同时进行,因此当判断之后,第一个线程还没结束,后续所有线程也都开始进行,就会出现超卖现象

死锁的产生案例

/**
 * 死锁的演示
 */
public class DeadLock {
    private static String fileA = "A文件";
    private static String fileB = "B文件";
    class Runner1 implements Runnable{
        @Override
        public void run() {
            while(true) {
                synchronized (fileA) {//打开文件A,线程独占
                    System.out.println(Thread.currentThread().getName() + ":文件A写入");
                    synchronized (fileB) {
                        System.out.println(Thread.currentThread().getName() + ":文件B写入");
                    }
                    System.out.println(Thread.currentThread().getName() + ":所有文件保存");
                }
            }
        }
    }
    class Runner2 implements Runnable{
        @Override
        public void run() {
            while(true) {
                synchronized (fileB) {//打开文件B,线程独占
                    System.out.println(Thread.currentThread().getName() + ":文件B写入");
                    synchronized (fileA) {
                        System.out.println(Thread.currentThread().getName() + ":文件A写入");
                    }
                    System.out.println(Thread.currentThread().getName() + ":所有文件保存");
                }
            }
        }
    }

    public void start(){
        new Thread(new Runner1()).start();
        new Thread(new Runner2()).start();
    }
    public static void main(String[] args) {
        new DeadLock().start();
    }
}

线程池的四种定义

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolSample1 {
    public static void main(String[] args) {
        //创建一个可创建一个定长线程池
        //定长线程池的特点是固定线程总数,空闲线程用于执行任务,如果线程都在使用,后续任务则处于等待状态
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        for(int i = 1; i <= 1000 ; i++){
            final int index = i;
            //不需要返回值,使用execute方法执行Runnable对象
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+":" + index );
                }
            });
            /*
            需要返回值,使用submit方法执行Callable对象,利用Future对象接收返回值
            Future<Object> ret = threadPool.submit(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    return null;
                }
            });
            */
        }
        //处理完毕关闭线程池
        threadPool.shutdown();
    }
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*演示*/
public class ThreadPoolSample2 {
    public static void main(String[] args) {
        //调度器对象
        //ExecutorService用于管理线程池
        ExecutorService threadPool = Executors.newCachedThreadPool();//创建一个可缓存线程池
        //可缓存线程池的特点是,无限大,如果线程池中没有可用的线程则创建,有空闲线程则利用起来
        for(int i = 1 ; i <= 1000 ; i++) {
            final  int index = i;
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ":" + index);
                }
            });
        }
        threadPool.shutdown();
    }
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolSample3 {
    public static void main(String[] args) {
        //调度器对象
        //ExecutorService用于管理线程池
        ExecutorService threadPool = Executors.newSingleThreadExecutor();//单线程线程池
        for(int i = 1 ; i <= 1000 ; i++) {
            final  int index = i;
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName() + ":" + index);
                }
            });
        }
        threadPool.shutdown();
    }
}
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ThreadPoolSample4 {
    public static void main(String[] args) {
        //调度线程池
        ScheduledExecutorService scheduledThreadPool =  Executors.newScheduledThreadPool(5);//可调度线程池
        //延迟1秒执行,每三秒执行一次
        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.out.println(new Date() + "延迟1秒执行,每三秒执行一次");
            }
        }, 1, 3, TimeUnit.SECONDS);
    }
}

 

posted @ 2024-01-09 21:59  她的回眸一直很美  阅读(16)  评论(0)    收藏  举报