zoukankan      html  css  js  c++  java
  • Java中的多线程

    1、 线程中的主要方法

        a) isAlive() 判断线程是否还活着,即线程是否未终止

        b) getPriority() 获得线程的优先级

        c) setPriority() 设置线程的优先级

        d) Thread.sleep() 设置线程休眠的时间

        e) jion() 把当前线程与该线程合并

        f) yield() 让出CUP

        g) 线程的优先级

                i. Thread.MIN_PRIORITY = 1 最小优先级

                ii. Thread.NORM_PRIORITY = 5 默认优先级

                iii. Thread.MAX_PRIORITY = 10 最大优先级

    2、 线程的中断

            a) Stop() 已过时,基本不用

            b) Interrupt() 简单,粗暴

            c) 推荐使用的是设置标志位

    3、 线程的高级操作

            a) wait() 使当前线程等待,直到被其线程唤醒

            b) notify() 唤醒等待的线程

    4、 实现同步的两种方式(主要是synchronized的使用)

            a) 锁代码块

                    i. Synchronized(object){要锁的代码块}

            b) 锁方法(推荐使用)

                    i. Synchronized void method(){}

    1、 Java多线程的实现主要有两个方式,一个是通过继承Thread类,一个是Runnable接口的实现。在使用多线程时主要用到两个方法一个是重写run()方法,用来实现将要执行的代码。第二个方法是start(),用来启动线程。

    2、 Thread类的实现

     1 public class ThreadDemo extends Thread{
     2  
     3     public void run(){
     4         for(int i = 0; i < 20; i++){
     5             System.out.println(Thread.currentThread().getName()+i);
     6         }
     7     }
     8     public static void main(String[] args) {
     9  
    10         ThreadDemo td1 = new ThreadDemo();
    11         td1.setName("线程1: ");
    12  
    13         ThreadDemo td2 = new ThreadDemo();
    14         td2.setName("线程2: ");
    15  
    16         //获取优先级
    17         System.out.println("线程一的优先级为:"+td1.getPriority());
    18  
    19         //设置线程的优先级优先级的值为0 - 10 从小到大
    20         td1.setPriority(MIN_PRIORITY);
    21         td2.setPriority(MAX_PRIORITY);
    22  
    23         td1.start();
    24         td2.start();
    25  
    26  
    27     }
    28  
    29 }

    1、 Runnable接口的实现

     1 ublic static void main(String[] args) {
     2         TicketRunnable tr = new TicketRunnable();
     3  
     4         Thread td1 = new Thread(tr);
     5         td1.setName("窗口1");
     6         Thread td2 = new Thread(tr);
     7         td2.setName("窗口2");
     8         Thread td3 = new Thread(tr);
     9         td3.setName("窗口3");
    10  
    11         td1.start();
    12         td2.start();
    13         td3.start();
    14     }
  • 相关阅读:
    今日大跌!
    web servers
    ASP.NET2.0缓存机制
    赚钱的总是史玉柱?
    asp.net速查手册
    为伊消得人憔悴,我的2007成就难有,内心彷徨
    success
    失守4600点
    Linux下chkconfig命令详解
    FTP批处理下载木马
  • 原文地址:https://www.cnblogs.com/ludashi/p/3865184.html
Copyright © 2011-2022 走看看