zoukankan      html  css  js  c++  java
  • 2-Java多线程编程

    一.线程与进程

    1.线程:程序中单独顺序的控制流。

               线程本身依靠程序进行运行。

               线程是程序中的顺序控制流,只能使用分配给程序的资源和环境。

    2.进程:执行中的程序。

               一个进程中可以包含一个或多个线程。

               一个进程中至少要包含一个线程。

    3.单线程:程序中只存在一个线程,实际上主方法就是一个主线程。

    4.多线程:多线程是在一个程序中执行多个任务,并发执行,抢先调度。

                  多线程的目的是更好的使用CPU资源。

    二.线程的常用方法

    1.取得线程名称:getName
    2.取得当前线程:currentThread
    3.判断线程是否启动:isAlive
    4.线程的强行运行:join
    5.线程的休眠:sleep
    6.线程的礼让:yield

    三.线程的优先级

     1 package com.example;
     2 class MyThread implements Runnable{
     3     public void run() {
     4         for (int i = 0 ; i < 5; i ++){
     5             try {
     6                 Thread.sleep(1000);
     7                 System.out.println(Thread.currentThread().getName()+":"+i);
     8             } catch (InterruptedException e) {
     9                 e.printStackTrace();
    10             }
    11 
    12         }
    13     }
    14 }
    15 public class MyClass {
    16     public static void main(String []args){
    17         Thread t6 = new Thread(new MyThread(),"a" );
    18         Thread t7 = new Thread(new MyThread(),"b" );
    19         Thread t8 = new Thread(new MyThread(),"c" );
    20         t6.setPriority(Thread.MIN_PRIORITY);
    21         t7.setPriority(Thread.NORM_PRIORITY);
    22         t8.setPriority(Thread.MAX_PRIORITY);
    23         t6.start();
    24         t7.start();
    25         t8.start();
    26 
    27     }
    28 }
    View Code

     四.线程的同步与死锁

    1.同步:通过人为的控制和调度,保证共享资源的多线程访问成为线程安全。(线程安全是指线程的调度顺序不影响任何结果,这个时候使用多线程,只需要考虑系统的内存,CPU是否够用即可)。

    (1)同步代码块

    synchronized(同步对象){

         需要同步的代码块;

    }

     (2)同步方法

    synchronized void 方法名称(){}

    2.死锁:

    学生找工作无经验(高薪);

    企业找职工给高薪(经验);

    四.线程的实现

    1.继承Thread类。

    2.实现Runnable接口。

    五.线程的状态

    1.创建

    2.就绪

    3.运行

    4.阻塞

    5.销毁

              

              

              

  • 相关阅读:
    how to use http.Agent in node.js
    How Node.js Multiprocess Load Balancing Works
    Child Process
    What does cmd /C mean? [closed] 关于nodejs的子进程部分
    Net
    二进制与十六进制的关系
    POJ 1201 Intervals (差分约束系统)
    POJ 1201 Intervals (差分约束系统)
    差分约束系统
    差分约束系统
  • 原文地址:https://www.cnblogs.com/BelieveFish/p/6687743.html
Copyright © 2011-2022 走看看