zoukankan      html  css  js  c++  java
  • 多线程概念与Thread类

    首先要了解什么是进程,一个程序正在运行,并且有独立的功能,这叫做进程。

    线程是指进程中的一个执行流程,一个进程中可以运行多个线程。

    线程:线程是进程中的一个执行单元,负责当前进程中程序的执行,一个进程至少有一个线程,一个进程也可以有多个线程,多个线程同时运行指的是来回高速切换

    程序运行的原理:

    分时调度:所有线程轮流使用,平均分给每个线程去使用。

    抢占时调度:先让优先级级别高的去使用,如果优先级相同的话,那么就进行线程随即分配,随即分配好比就是这个线程2秒,那个线程4秒,这种情况。

    创建多线程的两种方式:继承Thread类和实现Runnable接口。

    继承:

    1 定义一个类继承Thread。

    2 重写run方法。

    3 创建子类对象,就是创建线程对象。

    4 调用start方法

    package com.oracle.demo01;
    //定义一个类先继承Thread
    public class MyThread extends Thread {
    	//重写里面的run方法
    	public void run() {
    	  //getName()获取当前线程名称
    	  System.out.println("线程名称为:"+getName());
          for(int i=0;i<20;i++){
        	  System.out.println("MyThread-"+i);
           }
    	}
    }
    

      

    package com.oracle.demo01;
    
    public class Demo01 {
    		//为什么main方法不能调用getname()方法,因为main方法是静态的,静态不能调用非静态方法
    	   public static void main(String[] args) {
    		//获取执行当前代码的线程的线程对象
    		Thread th=Thread.currentThread();
    		System.out.println("主线程的名字:"+th.getName());
    		//创建新线程对象
    		MyThread thread=new MyThread();
    		//开启线程
    		thread.start();
    		for(int i=0;i<20;i++){
    			System.out.println("main-"+i);
    		}
    	}
    }
    

    run()方法是不需要用户来调用的,当通过start方法启动一个线程之后,当线程获得了CPU执行时间,便进入run方法体去执行具体的任务。继承Thread类必须重写run方法,在run方法中定义具体要执行的任务。

    start()用来启动一个线程,当调用start方法后,系统才会开启一个新的线程来执行用户定义的子任务,会为相应的线程分配需要的资源。

    实现Runnable接口:

    1、定义类实现Runnable接口。

    2、覆盖接口中的run方法。。

    3.  创建线程任务对象

    4、创建Thread类的对象

    5、将Runnable接口的子类对象作为参数传递给Thread类的构造函数。

    5、调用Thread类的start方法开启线程。

    package com.oracle.demo02;
    
    public class MyRunnable implements Runnable{
    	public void run() {
    		for(int i=0;i<20;i++){
    			System.out.println("thread-0"+i);
    		}
    		
    	}
    
    }
    

      

    package com.oracle.demo02;
    
    public class Demo01 {
    	   public static void main(String[] args) {
    		 //创建线程任务对象
    		  MyRunnable mr=new MyRunnable();
    		//创建Thread类对象
    		  Thread th=new Thread(mr);
    		//开启线程
    		 th.start();
    		 for(int i=0;i<20;i++){
    			 System.out.println("main"+i);
    		 }
    	}
    }
    

     Thread类与实现Runnable接口的区别:

        Thread类只能实现单继承,就相当于各做各的,完成各自的任务

        Runnable接口:避免了单继承的局限性,相当于拿出一个任务,给三个人共同去完成

  • 相关阅读:
    TextBox 只有下划线
    can't find web control library(web控件库)
    DropDownListSalesAC”有一个无效 SelectedValue,因为它不在项目列表中。
    IDE、SATA、SCSI、SAS、FC、SSD 硬盘类型
    如何打印1px表格
    CSS控制打印 分页
    Virtual Server could not open its emulated Ethernet switch driver. To fix this problem, reenable the Virtual Server Emulated Et
    Xml中SelectSingleNode方法中的xpath用法
    热带水果莫入冰箱?水果存放冰箱大法
    探索Asp.net的Postback机制
  • 原文地址:https://www.cnblogs.com/awdsjk/p/11064522.html
Copyright © 2011-2022 走看看