python与Java线程实现方式的对比

来源:互联网 发布:单片机程序实验流程图 编辑:程序博客网 时间:2024/06/13 11:19

1. python多线程的实现方式:

  • 继承Thread类
  • 实现Runnable接口
  • Callable接口+FutureTask包装器来创建Thread线程

    线程操作涉及到的方法:
    Thread:start启动 join加入新线程
    Lock/Rock:acquire():加锁 release(): 释放锁
    Condition:acquire():加锁 release(): 释放锁 wait notify notify_all
    Event: set()等同于notify_all clear() 取消notify_all
    time: sleep
    timer:Timer(interval function args=[] kwargs={})

  • interval: 指定的时间

  • function: 要执行的方法
  • args/kwargs: 方法的参数

python多线程实现的三种方式详解

2.Java多线程的实现方式:

  • 继承Thread类实现多线程
  • 实现Runnable接口方式实现多线程
  • 通过 Callable 和 Future 创建线程。

线程操作涉及到的方法:
start() 、stop() (过时) 、join() 、wait() 、sleep() 、notify() 、notifyAll()
Java多线程方法详解

JAVA多线程实现的三种方式详解

经典案例

共有四个和尚
其中一个和尚负责做馒头
其他三个和尚吃馒头
要求
当做馒头的时候,不能吃馒头
当吃馒头的时候不能做馒头
馒头上线只能是30个
在吃馒头的时候不能出现一个馒头被多个和尚吃
不能出现吃的时候和尚吃出异常(如一个和尚永远也吃不到,或者 一个和尚吃了一个不存在的馒头)

Java代码:

package com.dsj101.thread;  import java.util.ArrayList;  import java.util.List;  public class Test {     static class ManTou{         private int num;         public ManTou(int num) {             this.num = num;         }         @Override         public String toString() {             return "第"+num+"个";         }     }     public static List<ManTou> manTous=new ArrayList<>();     public static void main(String[] args) {         new HuoFu("大头和尚").start();         new ChiHuo("白眉和尚").start();         new ChiHuo("牛鼻子和尚").start();         new ChiHuo("花和尚").start();     }     //火夫     static class HuoFu extends Thread{         private String name;         public HuoFu(String name) {             this.name = name;         }         @Override         public void run() {             try {                 Thread.sleep(1000);             } catch (InterruptedException e) {                 e.printStackTrace();             }             while (true) {                 synchronized ("a") {                     System.out.println(name + "开始蒸馒头");                     for (int i = 0; i < 30; i++) {                         manTous.add(new ManTou(i + 1));                         System.out.println("做完第" + (i + 1) + "个码头");                         try {                             Thread.sleep(100);                         } catch (InterruptedException e) {                             e.printStackTrace();                         }                     }                     System.out.println("馒头做好了,开始吃吧");                     "a".notifyAll();                 }                 synchronized ("b") {                     try {                         System.out.println("我先去睡一会,没了叫我");                         "b".wait();                         System.out.println("我知道了开始做去");                     } catch (InterruptedException e) {                         e.printStackTrace();                     }                 }             }         }     }     //吃货     static class ChiHuo extends Thread{         private String name;         public ChiHuo(String name) {             this.name = name;         }         @Override         public void run() {              synchronized ("a"){                  try {                      "a".wait();                  } catch (InterruptedException e) {                      e.printStackTrace();                  }              }             ManTou m=null;             while (true) {                 synchronized ("a") {                     System.out.println(name + "开始吃馒头");                     if (manTous.size() != 0) {                         m = manTous.remove(0);                     } else {                         System.out.println(name + "发现没有馒头,叫醒火夫做馒头");                         synchronized ("b"){                             "b".notify();                         }                         try {                             System.out.println("我等着呢,完事后叫我吃");                             "a".wait();                         } catch (InterruptedException e) {                             e.printStackTrace();                         }                     }                 }                 if (m != null) {                     System.out.println(name + "消化馒头"+m.toString());                     int rd = (int) (Math.random() * 2000 + 1000);                     m = null;                     try {                         Thread.sleep(rd);                     } catch (InterruptedException e) {                         e.printStackTrace();                     }                 }             }         }     }  }  

python代码:

import threading  import time  mantous=[]  a=threading.Lock()  b=threading.Lock()  ca=threading.Condition(a)  cb=threading.Condition(b)  #火夫的任务函数  def huofu(name):      time.sleep(1)      while True:          ca.acquire()          for i in range(1,31):              mantous.append("第{0}个馒头".format(i))              print("做好第{0}个馒头".format(i))              time.sleep(0.1)          print("馒头做好,叫醒吃货")          ca.notify_all()          ca.release()          print("{0}去等到".format(name))          cb.acquire()          cb.wait()          cb.release()  #吃货的任务函数  def chihuo(name):      ca.acquire()      ca.wait()      ca.release()      while True:          m=None          ca.acquire()          if len(mantous) != 0 :              m=mantous.pop()          else:              print("没馒头了")              cb.acquire()              cb.notify()              cb.release()              ca.wait()          ca.release()          if m is not None:              print("{0}吃{1}".format(name,m))              time.sleep(1)  class Chuofu(threading.Thread):      def __init__(self,name):          #threading.Thread.__init__(self)          super(Chuofu,self).__init__()          self.name=name      def run(self):          time.sleep(1)          while True:              ca.acquire()              for i in range(1,31):                  mantous.append("第{0}个馒头".format(i))                  print("做好第{0}个馒头".format(i))                  time.sleep(0.1)              print("馒头做好,叫醒吃货")              ca.notify_all()              ca.release()              print("{0}去等到".format(self.name))              cb.acquire()              cb.wait()              cb.release()  class Cchihuo(threading.Thread):      def __init__(self,name):          threading.Thread.__init__(self)          self.name=name      def run(self):          ca.acquire()          ca.wait()          ca.release()          while True:              m=None              ca.acquire()              if len(mantous) != 0 :                  m=mantous.pop()              else:                  print("没馒头了")                  cb.acquire()                  cb.notify()                  cb.release()                  ca.wait()              ca.release()              if m is not None:                  print("{0}吃{1}".format(self.name,m))                  time.sleep(1)  # threading._start_new_thread(huofu,('大头和尚',))  # threading._start_new_thread(chihuo,('白眉和尚',))  # threading._start_new_thread(chihuo,('牛鼻子和尚',))  # threading._start_new_thread(chihuo,('花和尚',))  # t1=threading.Thread(target=huofu,args=('大头和尚',))  # t2=threading.Thread(target=chihuo,args=('白眉和尚',))  # t3=threading.Thread(target=chihuo,args=('牛鼻子和尚',))  # t4=threading.Thread(target=chihuo,args=('花和尚',))  # t1.start()  # t2.start()  # t3.start()  # t4.start()  Chuofu("大头和尚").start()  Cchihuo('白眉和尚').start()  Cchihuo('牛鼻子和尚').start()  Cchihuo('花和尚').start()  input()