【JAVA基础&Python】多线程


JAVA:
/*
*
* 1:定义一个继承Thread的类,里面定义run函数为需要多线程的业务函数
* 2:实例化重写的这个类,执行start方法进行多线程运行
*
* 测试Thread中的常用方法:
* 1. start():启动当前线程;调用当前线程的run()
* 2. run():通常需要重写Thread类中的此方法,将创建的线程要执行的操作声明在此方法中
* 3. currentThread():静态方法,返回执行当前代码的线程 * 4. getName()∶获取当前线程的名字 * 5. setName():设置当前线程的名字6. yield():释放当前cpu的执行权 * 7. join():在线程a中调用线程b的join(),此时线程a就进入阻塞状态,直到线程b完全执行完以后,线程a才结束阻塞状态。 * 8. stop():已过时。当执行此方法时,强制结束当前线程。 * 9. sleep(Long millitime):让当前线程′睡眠"指定的millitime毫秒。在指定的millitime毫秒时间内当前线程是阻塞状态。 * 10. isAlive():判断当前线程是否存活 *
*/ class MyThread extends Thread{ // 多线程 需要执行的方法 @Override public void run() { for (int i = 0; i < 100;i++){ if (i % 2 == 0){ System.out.println(i); } } } } // main 直接写就可以打印 public class ThreadTest { public static void main(String[] args) { // 继承重写的方法 MyThread t1 = new MyThread(); // 开始执行多线程 t1.start(); } }

 

 

/*
*
* 
* 线程的优先级:
* 1.MAX_PRIORITY: 10
* MIN_PRIORITY:1 * NORM_PRIORITY:5-->默认优先级 * 2.如何获取和设置当前线程的优先级:getPriority()︰
* 获取线程的优先级setPriority (int p):设置线程的优先级 * * *
*/ class MyThread extends Thread{ // 多线程 需要执行的方法 @Override public void run() { for (int i = 0; i < 100;i++){ if (i % 2 == 0){ System.out.println(Thread.currentThread().getPriority() + ":" + i); } } } } // main 直接写就可以打印 public class ThreadTest { public static void main(String[] args) { // 继承重写的方法 MyThread t1 = new MyThread(); // 在执行之前设置优先级 t1.setPriority(Thread.MAX_PRIORITY); // 开始执行多线程 t1.start(); } }

 

 

 
#!/usr/bin/python3   Python的多线程是加了锁的,所以Python在使用时最好使用进程池,多进程,它的多线程是个伪多线程
import _thread
import time

# 为线程定义一个函数
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print ("%s: %s" % ( threadName, time.ctime(time.time()) ))

# 创建两个线程
try:
   _thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   _thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print ("Error: 无法启动线程")

while 1:
   pass
posted @ 2020-12-29 10:17  PythonNew_Mr.Wang  Views(126)  Comments(0Edit  收藏  举报