多线程

什么是多线程?多线程与一般的程序不同,一般的程序都是单线顺序执行的,而多线程则是多个程序同时执行。一般的程序就是一个干十个人的活,而多线程则是十个人干十个人的活;


image.png
  • 多线程的两种实现方法
    package code;

    public class Textthread {
    
    public static void main(String[] args) {
      Thread coding = new Coding();
      Thread print = new Thread(new Print());
      
      coding.start();
      print.start();
      System.out.println("你好啊");
      
     }
    }
    
    class Coding extends Thread {
    public void run() {
      for (int i = 0; i < 100; i++) {
          System.out.println("小明打了" + i + "行代码");
          try {
              Thread.sleep(2);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
    }
    }
    
    class Print implements Runnable {
       public void run() {
        long startTime = System.currentTimeMillis();
           for (int i = 0; i < 200; i++) {
             System.out.println("小明打印了" + i + "页材料");
                try {
                    Thread.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            long endTime = System.currentTimeMillis();
       System.out.println("共用时" + (endTime -startTime) + "ms");
    }
     }
    
  • 线程的等待

           public class ProducerAndConsumer {
    
              public static void main(String[] args) {
                   Box box = new Box();
                   Thread producer = new Producer(box);
                   Thread consumer = new Consumer(box);
                   producer.start();
                  consumer.start();
               }
           }
    
           class Box{
              public int boxValue = 0;
         }
    
    class Producer extends Thread{
        Box box;
        public Producer(Box box){
            this.box = box;
        }
        public void run(){
            for(int i = 1; i<6; i++){
               synchronized(box){
                 while(box.boxValue!=0){
                    System.out.println("Producer: 盒子非空,进入等待队列");
                     try {
                        box.wait();
                    } catch (InterruptedException e) {
                         e.printStackTrace();
                    }
                }
                box.boxValue = i;
                System.out.println("盒子中放入了"+i+",并通知其他等待者");
                 box.notify();
               }
             }
        }
     }
    
    
    class Consumer extends Thread{
          Box box;
        public Consumer(Box box){
            this.box = box;
        }
        public void run(){
            for(int i = 1; i<6; i++){
               synchronized(box){
                while(box.boxValue==0){
                    System.out.println("Consumer: 盒子为空,进入等待队列");
                     try {
                        box.wait();
                     } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                box.boxValue -= i;
                System.out.println("从盒子取出了"+i+",并通知其他等待者");
                 box.notify();
              }
            }
        }
    }
    
  • 锁的实现
    public class ThreadAccount {

         public static void main(String[] args) {
             BankAccount account = new BankAccount();
      Thread husband = new BankThread(account);
      Thread wife = new BankThread(account);
      husband.start();
      wife.start();
      
         }
     }
    
    
    class BankAccount {
         private double balance = 1000;
         public boolean isSuccess(double add){
             if(add<=0){
                 return false;
             }else{
                 synchronized(this){
                     System.out.println("当前的余额为:"+balance);
                    try {
                        Thread.sleep(3);
                     } catch (InterruptedException e) {
                         e.printStackTrace();
                    }
                   balance += add;
                     System.out.println("新的余额为:"+balance);
                 }
                 return true;
             }
        }
     }
    class BankThread extends Thread{
        BankAccount account;
        public BankThread(BankAccount account){
            this.account = account;
        }
        public void run(){
            account.isSuccess(200);
        }
    }
    
  • 死锁

    public class DeadLock {
    
        public static void main(String[] args) {
            Object lock1 = new Object();
            Object lock2 = new Object();
            Thread thread1 = new ThreadA(lock1,lock2);
            Thread thread2 = new ThreadB(lock1,lock2);
             thread1.start();
             thread2.start();
         }
    }
    
    class ThreadA extends Thread{
         Object lock1;
         Object lock2;
         public ThreadA(Object lock1, Object lock2){
             this.lock1 = lock1;
            this.lock2 = lock2;
        }
        public void run(){
            synchronized(lock1){
                 System.out.println("A拿到了lock1");
                 try {
                    Thread.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                 }
                synchronized(lock2){
                     System.out.println("A拿到了lock1和lock2");
                }
            }
        }
    }
    
    
    
    class ThreadB extends Thread{
        Object lock1;
        Object lock2;
        public ThreadB(Object lock1, Object lock2){
            this.lock1 = lock1;
            this.lock2 = lock2;
        }
        public void run(){
            synchronized(lock2){
                System.out.println("B拿到了lock2");
                try {
                    Thread.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized(lock1){
                     System.out.println("B拿到了lock1和lock2");
                }
           }
         }
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,192评论 19 139
  • 本文主要讲了java中多线程的使用方法、线程同步、线程数据传递、线程状态及相应的一些线程函数用法、概述等。 首先讲...
    李欣阳阅读 7,229评论 1 15
  • Java多线程学习 [-] 一扩展javalangThread类 二实现javalangRunnable接口 三T...
    影驰阅读 8,125评论 1 18
  • 【 线程间的通讯 wait()在对象上等待,等待通知(在等待过程中释放对象锁、等待必须在同步块内、这个对象就是同步...
    征程_Journey阅读 4,014评论 0 0
  • 你不急躁,于是清流如水般涌入心扉,寂静深夜,依然婉转。
    馄饨绿豆精阅读 1,364评论 0 0

友情链接更多精彩内容