多线程(Multi-Threading)

Creating threads in Java

Two things to do to create threads in java:

  (1) Create a task (object)

  //Creating a task

  public class TaskClass implements Runnable {

    public TaskClass() { ... }

  //Implement the run method in Runnable

  void run() {

   //things to do in the task }

   }

  //Runnable interface

  public interface Runnable {

     void run();

   }

   (2) Create a thread and combine the task with the thread (object)

  1 way

  //Create a task class

  public class TaskClass implements Runnable {

     public TaskClass(...) { ... }

  //Implement the run method in Runnable

    void run() {

       //things to do in the task

    }

  }

  public class ThreadDemo{

    public void someMethod(){

    //Create an instance of TaskClass

    TaskClass task=new TaskClass(...);

    //Create a thread

    Thread thread=new Thread(task);

     //Start a thread

    thread.start();

    }

   }

  2 way

  //Custom thread class

  public class CustomThread extends Thread {

    public CustomThread( ) { ... }

    //Override the run method in Runnable

    void run() {

     //things to do in the task

    }

   }

  public class ThreadDemo{

    public void someMethod(){

    //Create a thread

     CustomThread thread1=new CustomThread( );

     //Start a thread

    thread1.start();

     //Create another thread

    CustomThread thread2=new CustomThread( );

    //Start a thread

    thread2.start();

     }

     }

main Thread

  When a program starts, the main Thread automatically starts

  The default name of the Thread: main with priority 5

  public static void main(String[] args){

    System.out.println("Current thread: " + Thread.currentThread());

    Thread.currentThread().setName("MyThread");

    System.out.println("After name change: " + Thread.currentThread());

  }

Example: create threads

  public class ThreadDemo1 {

    public static void main(String[] args) {

    String hw= “do home work”;

     String tv= “watch TV”;

    DoSomething doHW= new DoSomething( hw );

    DoSomething watchTV = new DoSomething( tv );

     }

  }

  

  public class DoSomething {

    private String doWhat;

    public DoSomething(String aThing) {

    this.doWhat = aThing;

    doIt();

  }

     public void doIt(){

     for (int i=0;i<5;i++)

    System.out.println(doWhat+": "+i);

   }

   }

并没有使用多线程

Create threads (solution 1)

  public class ThreadDemo1 {

    public static void main(String[] args) {

      DoSomething doHW= new DoSomething("do home work");

      DoSomething watchTV = new DoSomething(“watch TV");

      Thread hwThread= new Thread(doHW);

      Thread tvThread = new Thread(watchTV);

      hwThread.start();

      tvThread.start();

      }

    }

  public class DoSomething implements Runnable {

   private String doWhat;

  public DoSomething(String aThing) {

   this.doWhat = aThing;

  } public void run(){

  for (int i=0;i<5;i++)

  System.out.println(doWhat+": "+i);

   }

   }

Create threads solution 2

  public class ThreadDemo2 extends Thread {

    String doThing;

    ThreadDemo2(String doWhat){

    this.doThing=doWhat;

    }

  public static void main(String[] args) {

    String hw= "do home work";

    String tv= "watch TV";

    ThreadDemo2 thread1=new ThreadDemo2(hw);

    ThreadDemo2 thread2=new ThreadDemo2(tv);

    thread1.start();

    thread2.start();

    }

  public void run() {

    for(int i=0;i<5;i++)

      System.out.println(doThing+": "+i);

     }

  }

Control  a  Thread  

  public static void yield():

    Causes the currently executing thread object to temporarily pause

    Allow other threads to execute(执行)

    aThread.yield();

    t1.yield();

    t2.sleep(1000);

  static void sleep(long millis): 

    Causes the currently executing thread to sleep (block) for the specified number of milliseconds

    If the thread is blocked by sleep or wait, an InterruptedException is thrown

    try {

      aThread.sleep(1000);

      //sleep for 1 second

      } catch (InterruptedException ex) {

      //do sth…

      }

  interrupt():

   Does not stop a thread Set "interrupted" status to true Why interrupt?

  After interrupt is set, we can take actions

  isInterrupted():

  Tests whether this thread has been interrupted.

  The interrupted status of the thread is unaffected by this method.

    if(isInterrupted()){

         Action

        }

  interrupted():

  Tests whether the current thread has been interrupted.

  The interrupted status of the thread is cleared by this method.

  Returns: true if the current thread has been interrupted; false otherwise.

  public class ThreadDemo2 extends Thread {

    String doThing;

     ThreadDemo2(String doWhat){

      this.doThing=doWhat;

    }

    public static void main(String[] args) {

    String hw= "do home work";

    String tv= "watch TV";

    ThreadDemo2 thread1=new ThreadDemo2(hw);

    ThreadDemo2 thread2=new ThreadDemo2(tv);

    thread1.start();

    thread2.start();

     }

    public void run() {

      for(int i=0;i<5;i++) {

      System.out.println(doThing+": "+i);

      this.yield();

      }

    }

  }

  public class ThreadDemo2 extends Thread {

    String doThing;

    ThreadDemo2(String doWhat){

     this.doThing=doWhat;

     }

    public static void main(String[] args) {

    String hw= "do home work";

    String tv= "watch TV";

    ThreadDemo2 thread1=new ThreadDemo2(hw);

    ThreadDemo2 thread2=new ThreadDemo2(tv);

    thread1.start();

     thread2.start();

    }

    public void run() {

    for(int i=0;i<5;i++) {

     System.out.println(doThing+": "+i);

    try {

       this.sleep(10);

      } catch (InterruptedException ex) {

      System.out.println(“sth wrong”);

       }

     }

    }

   }

Synchronization

  Two or more threads share the same resource Synchronized method:

  To make a method synchronized: add the synchronized keyword to its declaration

  When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object

end19

时间: 2024-10-19 02:47:42

多线程(Multi-Threading)的相关文章

Python多线程(threading)学习总结

注:此文除了例子和使用心得是自己写的,很多都是Python核心编程中的原文.原文文风应该能看出来,就不每个地方单独表明出处了. 线程(有时被称为轻量级进程)跟进程有些相似,不同的是,所有的线程运行在同一个进程中,共享相同的运行环境.它们可以想像成是在主进程或"主线程"中并行运行的"迷你进程". 线程有开始,顺序执行和结束三部分.它有一个自己的指令指针,记录自己运行到什么地方.线程的运行可能被抢占(中断),或暂时的被挂起(也叫睡眠),让其它的线程运行,这叫做让步.一个

Python3 多线程 学习 threading

#-*- coding:utf-8 --*- #多线程测试 import time import datetime import threading def worker(): print("未用多线程") time.sleep(1) return def worker2(): print("使用多线程") time.sleep(1) return if __name__ == "__main__" : d1 = datetime.datetim

Python学习笔记16:标准库之多线程(threading包)

Python主要通过标准库中的threading包来实现多线程. 当今网络时代,每个服务器都会接收到大量的请求.服务器可以利用多线程的方式来处理这些请求,以提高对网络端口的读写效率. Python是一种网络服务器的后台工作语言 (比如豆瓣网),所以多线程也就很自然被Python语言支持. 多线程售票以及同步 我们使用Python来实现Linux多线程与同步文中的售票程序. 我们使用mutex (也就是Python中的Lock类对象) 来实现线程的同步: import threading impo

Python学习笔记16:标准库多线程(threading包裹)

Python主要是通过标准库threading包来实现多线程. 今天,互联网时代,所有的server您将收到大量请求. server要利用多线程的方式的优势来处理这些请求,为了改善网络port读写效率. Python它是一个网络server后台工作语言 (豆瓣网),所以多线程也就非常自然被Python语言支持. 多线程售票以及同步 我们使用Python来实现Linux多线程与同步文中的售票程序. 我们使用mutex (也就是Python中的Lock类对象) 来实现线程的同步: import th

Python 多线程 -thread threading Queue- 简单学习

在实际工作过程中,会出现需要并发的做一些事情,例如一台机器测到几千台机器的网络连通性,如果你单线程一台一台测的话,会花费很多的事情,不具有实时性,更不能在变化的时候立刻感知当时网络的状况,这时多线程就是一个很好地选择.python已经给我们封装好了多线程库thread和threading. thread:比较底层的模块 threading:Higher-level threading interface ps:建议使用threading模块 - 高级别的threading模块更为先进,对线程的支

python 多线程并发threading &amp; 任务队列Queue

https://docs.python.org/3.7/library/concurrency.htmlpython程序默认是单线程的,也就是说在前一句语句执行完之前后面的语句不能继续执行先感受一下线程,一般情况下: def testa(): sleep(1) print "a" def testb(): sleep(1) print "b" testa() testb()#先隔出一秒打印出a,再过一秒打出b 但是如果用了threading的话: ta = thre

Python之多线程:Threading模块

1.Threading模块提供的类 Thread,Lock,Rlock,Condition,Semaphore,Event,Timer,local 2.threading模块提供的常用的方法 (1)threading.currentThread(): 返回当前的线程变量. (2)threading.enumerate(): 返回一个包含正在运行的线程的list.正在运行指线程启动后.结束前,不包括启动前和终止后的线程. (3)threading.activeCount():返回正在运行的线程数量

线程:主线程、子线程 同步线程、异步线程 单线程、多线程 System.Threading与System.Windows.Threading

入门-------------------------------------------------------------------------------- 概述与概念    一个C#程序开始于一个单线程,这个单线程是被CLR和操作系统(也称为“主线程”)自动创建. 创建和开始使用多线程    public Window1()    {        //主线程         //Code……        //使用匿名方法来启动子线程        Thread t = new Th

python多线程与threading模块

python多线程与_thread模块 中介绍了线程的基本概念以及_thread模块的简单示例.然而,_thread模块过于简单,使得我们无法用它来准确地控制线程,本文介绍threading模块,它提供了更强大的多线程管理方案. threading模块的对象 Thread 表示一个执行线程的对象 Lock 锁原语 RLock 可重入锁对象,使单一线程可以再次获得已持有的锁(递归锁) Condition 条件变量对象,使得一个线程等待另一个线程满足特定条件 Event 条件变量的通用版本,任意数量

多线程(threading module)

一.线程与进程 线程定义:线程是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务. 进程定义:An executing instance of a program is called a process.(程序的执行实例称为进程.) 线程与进程的区别: 1. 线程共享创建它的进程的地址空间; 进程有自己的地址空间. 2. 线程可以直接访问其进程的数据段; 进程拥有自己父