python与Java线程实现方式的对比
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()
转载于:https://www.cnblogs.com/cn-7876/p/7757776.html
python与Java线程实现方式的对比相关推荐
- java线程实现方式
线程的实现 各个线程既可以共享进程资源(内存地址.文件I/O等),又可以独立调度(线程是CPU调度的基本单位). 每个已经执行start()且还未结束的java.lang.Thread类的实例就代表了 ...
- 使用Python,OpenCV线程化方式提高视频FPS(每秒帧数)
使用Python,OpenCV处理视频流时,获得更高FPS(Frams Per Second)的"秘密"是将I / O(即从摄像机传感器读取帧)交给线程去处理: 读取帧 I/O是阻 ...
- PYTHON解析XML的多种方式效率对比实测
在最初学习PYTHON的时候,只知道有DOM和SAX两种解析方法,但是其效率都不够理想,由于需要处理的文件数量太大,这两种方式耗时太高无法接受. 在网络搜索后发现,目前应用比较广泛,且效率相对较高的E ...
- java线程创建方式_Java创建线程安全的方法
原文链接 译者:秦建平 校对:方腾飞 首先来看一个问题: 下面这个方法是线程安全的吗?如何才能让这个方法变成线程安全的? public class MyCount { private static i ...
- 深度对比 Python 与 Java 的区别(一)
引入 高中有一好友,在大学期间苦练 Java,各类八股文烂熟于心,最终进入某大厂却在维护 Python 项目. 而本人不思进取,不想背八股文,于是大学期间只是苟着写 Python,然而却最终进入某互联 ...
- (二)Java线程与系统线程,生命周期
本专栏多线程目录: (一)线程是什么 (二)Java线程与系统线程和生命周期 (三)Java线程创建方式 (四)为什么要使用线程池 (五)四种线程池底层详解 (六)ThreadPoolExecutor ...
- 并发编程四:深入理解java线程
文章目录 深入理解java线程 线程基础知识 线程的同步互斥 上下文切换(Context switch) 线程的生命周期 操作系统层面线程生命周期 Java线程的生命周期 java线程详解 java线 ...
- 学python和java哪个难?,java和python哪个难学
java和python哪个好学 ①python比Java简单,学习成本低,开发效率高;②Java运行效率高于python,尤其是纯python开发的程序,效率极低;③Java相关资料多,尤其是中文资料 ...
- java 创建线程_【80期】说出Java创建线程的三种方式及对比
点击上方"Java面试题精选",关注公众号 面试刷图,查缺补漏 >>号外:往期面试题,10篇为一个单位归置到本公众号菜单栏->面试题,有需要的欢迎翻阅. 一.Ja ...
最新文章
- 如何设计一个本地缓存
- Java基础篇:Executor框架
- python连接字符串的join
- 少年宫计算机室活动小结,微机室管理工作总结
- 泊松图像融合(泊松融合)
- MOXA的Nport5600初始密码
- Nancy简单实战之NancyMusicStore(二):打造首页
- KNN识别手写体数字
- (计算机组成原理)第七章输入和输出系统-第三节:I/O接口
- ECCV18|这篇论文开源的车牌识别系统打败了目前最先进的商业软件(附Github地址)...
- VSA Cluster中小企业无SAN环境解决方案
- metadata文件_用Kubernetes部署Springboot或Nginx,也就一个文件的事
- 三菱伺服驱动器示例_三菱伺服电机+编码器(伺服控制器)的接线示例
- 期货客户开户手续费(期货开户最低手续费)
- 【机器学习】机器学习泛泛之谈
- STM32通用定时器实现us微秒延时
- 2019考研 | 天津大学计算机专硕复试131.25分考研经历与经验总结(复试)
- 符合OpenDRIVE规范的xodr文件格式解读(1) ——road部分
- MySQL获取当前时间的各种方式
- glut 配置,解决“gl/glut.h”: No such file or directory