多线程(基础)Python、Java实现

66 篇文章 0 订阅

大二学习Java时第一次接触了多线程的概念,但是当时并不理解,只是知道大体的概念。

如今确成为了大三狗,开设了操作系统这门课。如今回首当年,貌似又懂了什么。

 

一个程序有多个进程,而一个进程里会有多个线程。

编程语言中,使用多线程是为了让程序同时干多个事情,让它能一心多用

不谈原理,简单讲讲线程是怎么在计算机里混的:多个线程排好队列,等待CPU的计算,每个线程被分配给固定的时间放到CPU上运行,不管线程运行还是没运行完,都要从CPU离开,然后排到队尾继续等待CPU的计算,直到计算完成撤离内存。这样在宏观上来看,CPU在1秒内同时在干多件事。嗯,神奇。

 

下面附上Python和Java多线程的实现:

Java:两种方式 

1、继承Thread类,然后把逻辑重写在run()方法中,实例化该对象后,调用start()方法启动线程

2、定义实现Runnable接口的类,在该类中实现run()方法,新建一个Thread对象,把实现Runnable接口的对象传给Thread的构造方法,通过Thread的start()方法启动线程。(ps:这个方法太麻烦,一般用第一个,但是Java只能继承一个父类,所以,遇到冲突的时候用第二个方法吧)

第一种:

class Thread1 extends Thread{
	public void run() {
		System.out.println(Thread.currentThread().getName());//获取线程名字
	}
}

public class Threadtest {
	public static void main(String[] args) {
		Thread1 thread1=new Thread1();
		thread1.start();
	}
}

第二种: 

class RenWu implements Runnable{
	public void run() {
		System.out.println("当前进程"+Thread.currentThread().getName());
	}
}

public class Threadtest {
	public static void main(String[] args) {
		RenWu rw =new RenWu();
		Thread thread=new Thread(rw);
		thread.start();
	}
}

 

Python:

第一个参数是线程函数变量,第二个参数args是一个数组变量参数,如果只传递一个值,就只需要i, 如果需要传递多个参数,那么还可以继续传递下去其他的参数,其中的逗号不能少,少了就不是数组了,就会出错。

import threading
def thread_job():
    print('This is a thread of %s' % threading.current_thread())

def main():
    thread = threading.Thread(target=thread_job, )  # 定义线程 target指定目标
    thread.start()  # 让线程开始工作

if __name__ == '__main__':
    main()

注意:如果一个值的话 

t1 = threading.Thread(target=run_thread, args=(5,))  #要在5的后面加入,

import time, threading

# 假定这是你的银行存款:
balance = 0

def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

def run_thread(n):
    for i in range(100000):
        change_it(n)

t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print(balance)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值