zoukankan      html  css  js  c++  java
  • 多线程

    世界上本没有多线程,cpu故意在各个线程中跳转,就假装有了多线程

    测试的时候语句少的一下被执行完,要增加多点语句才能测试出来恰恰说明了这个原理

    线程的实现由两种方法

    1)继承Thread,然后重写run方法,(不能漏掉public

    class SpackA extends Thread{
    SpackA a=new SpackA();

    2)运用Thread(Runnable target),run方法改在Runnable接口里面实现

    class SpackA implements Runnable{
    Thread a=new Thread(new SpackA());

    线程有优先级,默认是5,既是Thread.NORM_PRIORITY,最大Thread.MIN_PRIORITY,最小Thread.MAX_PRIORITY

    setPriority()//在try语句中执行
    getPriority()

    一些知识

    sleep(int millsecond)要在try-catch块中进行

    isAlive()可以检测线程是否生存,(run方法开始运行到结束就是生存的)

    类方法currentThread()返回当前调用的线程

    线程不要重新赋值,因为旧的线程不会被垃圾回收机制回收,还会继续发挥作用

    interrupt()可以重新激活sleep的程序,在sleep的try-catch块里面会发出异常

    import java.io.*;
    import java.util.Scanner;
    import java.sql.*;
    
    public class Test {
        public static void main(String args[]){
            demo demo1=new demo();
            demo1.student=new Thread(demo1);
            demo1.teacher=new Thread(demo1);
            demo1.student.start();
            demo1.teacher.start();
        }
    }
    
    class demo implements Runnable{
        Thread student,teacher;
        
        @Override
        public void run() {
            // TODO 自动生成的方法存根
            if(Thread.currentThread()==student){
                System.out.println("sleep");
                try {
                    student.sleep(10000);
                } catch (InterruptedException e) {
                    // TODO 自动生成的 catch 块
                    System.out.println("ririri");
                }
                System.out.println("shangke");
            }
            else if(Thread.currentThread()==teacher){
                for(int i=0;i<3;i++){
                    System.out.println("upup");
                }
                student.interrupt();
            }
        }
        
    }
  • 相关阅读:
    C#的内存管理原理解析+标准Dispose模式的实现
    深入理解C#:编程技巧总结(二)
    深入理解C#:编程技巧总结(一)
    深刻理解:C#中的委托、事件
    你知道JavaScript中的结果值是什么吗?
    switch语句的妙用
    相等比较、关系比较总结
    用ServiceStack操作使用redis的问题
    springmvc 处理put,delete请求
    easyui 验证动态添加和删除问题
  • 原文地址:https://www.cnblogs.com/vhyc/p/6075783.html
Copyright © 2011-2022 走看看