线程的创建和简单的使用

java中的创建线程的两种方法:

1.创建一个类继承Thread

2.创建一个类去实现Runnable

实现的Runnable方法比继承Thread的方法更加的灵活

买票实例的两种实现方法

  

 class Ticket extends Thread
 2 {
 3     private static int num = 50; //定义成static,四个线程共享50张票。
 4     public void run()
 5     {
 6         while(num>0)
 7         System.out.println(Thread.currentThread().getName()+"...sale..."+num--);
 8     }
 9 }
10 
11 class Maipiao
12 {
13     public static void main(String[] args) 
14     {
15         Ticket win1 = new Ticket();
16         Ticket win2 = new Ticket();
17         Ticket win3 = new Ticket();
18         Ticket win4 = new Ticket();
19 
20         win1.start();
21         win2.start();
22         win3.start();
23         win4.start();
24     }
25 }
 
第二种:
 
//这个类只是为了描述线程的任务,跟线程没有任何关系。
 2 class Ticket implements Runnable
 3 {
 4     private int num = 50; 
 5     public void run()
 6     {
 7         while(num>0)
 8         System.out.println(Thread.currentThread().getName()+"...sale..."+num--);
 9     }
10 }
11 
12 class Maipiao
13 {
14     public static void main(String[] args) 
15     {
16         Ticket t = new Ticket();
17         
18         Thread win1 = new Thread(t);
19         Thread win2 = new Thread(t);
20         Thread win3 = new Thread(t);
21         Thread win4 = new Thread(t);
22 
23         win1.start();
24         win2.start();
25         win3.start();
26         win4.start();
27     }
28 }

 
 
以上的两种方法案例的线程都是不安全的如果要是线程安全的要加上线程锁
 
 
 
  线程锁的使用主要是在run方法中把要循环的东西用synchronized (this){}括起来或者把run方法用public synchronized void run() {}修饰 

这样就可以是运行的方法不会出现多个线程同时运行的错误  

 java中线程还有许多的方法使线程睡眠的方法 sleep(),礼让的方法yield()等等 我们在使用线程的时候为了让某一个线程先执行我们还可以设置他的优先级,具体使用方法查看api帮助文档

 Python的线程的使用

线程:
       python中的线程是伪线程
       进程中的每一个子任务,不能独立存在
       进程:独立的所有子任务的集合
       线程 进程 :目的都是想同时完成任务
       进程特点:进程的特点是独立(内存独立,cpu使用独立)启动进程开销大,进程直接间很难共享数据,和数据通信,数据安全高
       线程特点:依赖进程(内存是共享的,CPU独占)启动开销小,线程之间容易共享数据容易通讯,线程不安全

      
       Python:创建线程的两种方式
         两种方式:函数和类
        
	 python2: thread
         python3:_thread
                  threading(引入的模块)

python2和python3引入的模块是不一样的注意使用
 
函数方式的线程
'''
函数
'''
import  threading
import time
def something():
    for i in range(1,11):
        print(i)
        time.sleep(1)
threading._start_new_thread(something,())
print("mian....")
input()
'''

 

'''
类的方式
start:注意重写了Start一定要调用父类的start

run:使用户的任务方法会在start之后自动调用

join:线程阻塞方法,谁调用join,阻断谁。直到join中指定的时间,或者run代码执行完了
'''
class Mythread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        print("Mythread")
    def run(self):
        for i in range(1,11):
             print(i)
             time.sleep(1)

    def start(self):
        print("开始Mythread")
        threading.Thread.start(self)
print("mian....")
t=Mythread()
t.start()
t.join()


python的线程安全,因为python是一种伪线程所以需要借助一个锁threading.Lock()#锁

以下案例中是线程的安全有线程锁的使用

class Thread1(threading.Thread):
    def run(self):
        for i in range(1,11):
            if i==3:
                condition.acquire()#上锁
                condition.wait()
                condition.release()#解锁
            print(i)
            time.sleep(1)

class Thread2(threading.Thread):
    def run(self):
        for i in range(30,19,-1):
            if i==25:
                condition.acquire()
                condition.notify()
                condition.release()
            print(i)
            time.sleep(1)
lock=threading.Lock()#锁
condition=threading.Condition(lock=lock)#锁的方法
Thread1().start()
Thread2().start()

最后个大家一个生产者消费模式:

 需求:四个和尚,一个做馒头的三个吃馒头的,做馒头的需要先做10个馒头然后叫醒三个吃馒头的,之后自己进入休眠
三个和尚一个一个去拿馒头,只要有一个和尚发现没馒头了,就去叫醒做馒头的,之后三个吃馒头的去进行休眠
就这样一直循环。 这个案例在完成后可以一直循环的运行
class zhengThread(threading.Thread):
    def __init__(self,name=None):
        threading.Thread.__init__(self);
        self.name=name
    def run(self):
        while True:
            condition.acquire()
            if len(guo) == 0:
                for i in range(1,11):
                    guo.append(i)
                    print("做出第{0}个馒头".format(i))
                    time.sleep(1)
                condition.notify_all()
            condition.release()
            condition2.acquire()
            condition2.wait()
            condition2.release()

class chiThread(threading.Thread):
    def __init__(self,name=None):
        threading.Thread.__init__(self);
        self.name=name
    def run(self):
        while True:
            mantou=None
            condition.acquire()
            if len(guo) == 0:
                condition2.acquire()
                condition2.notify()
                condition2.release()
                condition.wait()
            else:
                mantou=guo.pop()
            condition.release()
            if mantou is not None:
                print("{0}正在开始吃第{1}个馒头".format(self.name,mantou))
                time.sleep(random.choice([1,2,3,4,5]))

import random
guo=[]
lock=threading.Lock()
condition=threading.Condition(lock=lock)    #吃的锁

lock2=threading.Lock()
condition2=threading.Condition(lock=lock2)  #蒸的锁

zhengThread(name="大头和尚").start()
chiThread(name="白眉和尚").start()
chiThread(name="花和尚").start()
chiThread(name="牛鼻子和尚").start()

这个线程呢是典型的消费者模式,有兴趣的可以研究下,这个里面呢我写了两个锁就是为了防止死锁的出现,死锁呢会造成方法

在运行过程中停止运行,这是常见的,有兴趣的可以研究下锁的使用





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值