Java及Python线程实现方式带实例

本文通过实例介绍了Java和Python两种语言中线程的实现方式,包括继承Thread类、实现Runnable接口、使用Callable+FutureTask接口以及Python的线程类和函数。在Java中,通过模拟和尚做馒头和吃馒头的过程展示了线程同步和通知机制的运用,而在Python中,使用了Lock、Condition等工具进行线程控制。

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

一、线程实现方式:
    1.继承Thread类
    2.实现Runnable接口
    3.实现Callable+FutureTask接口
线程操作涉及到的方法
      start:线程对象的方法
      sleep:普通对象的方法
      join:线程对象的方法
     wait:普通对象的方法
     notify:普通对象的方法
     notifyAll:普通对象的方法
实例:
共有四个和尚
其中一个和尚负责做馒头
其他三个和尚吃馒头
要求
 当做馒头的时候,不能吃馒头
 当吃馒头的时候不能做馒头
 馒头上线只能是30个
 在吃馒头的时候不能出现一个馒头被多个和尚吃
 不能出现吃的时候和尚吃出异常来(如一个和尚永远也吃不到,或者一个和尚吃了一个不存在的馒头)
package com.dsj101.thread;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by seal on 2017/6/25.
 */
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线程实现的方式:
  1.类
  2.函数
线程操作涉及到的方法
 对象:
    Thread:start(启动线程)  join加入新线程
    lock、Rlock:acquire(枷锁)  release(释放锁)
    Condition :acquire(枷锁)  release(释放锁)  wait  notify  notify_all
    Event: isSet()    set()等同于notify  clear 取消notifyAll
    time:等同于java中的sleep
    timer:Timer(interval, function, args=[], kwargs={})
              interval: 指定的时间
              function: 要执行的方法
              args/kwargs: 方法的参数
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()



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值