zoukankan      html  css  js  c++  java
  • 62.Java线程常见的方法

    线程常见的方法

    Thread(String name)     初始化线程的名字

     getName()             返回线程的名字

     setName(String name)    设置线程对象名

     sleep()                 线程睡眠指定的毫秒数。

     getPriority()             返回当前线程对象的优先级   默认线程的优先级是5

     setPriority(int newPriority) 设置线程的优先级    虽然设置了线程的优先级,但是具体的实现取决于底层的操作系统的实现(最大的优先级是10 ,最小的1 , 默认是5)。

     currentThread()      返回CPU正在执行的线程的对象

    class ThreadDemo1 extends Thread
    {
        public ThreadDemo1(){
          
        }
        public ThreadDemo1( String name ){
           super( name );
        }
        
        public void run(){
           int i = 0;
           while(i < 30){
              i++;
              System.out.println( this.getName() + " "+ " : i = " + i);
              System.out.println( Thread.currentThread().getName() + " "+ " : i = " + i);
              System.out.println( Thread.currentThread() == this );
              System.out.println( "getId()" + " "+ " : id = " + super.getId() );
              System.out.println( "getPriority()" + " "+ " : Priority = " + super.getPriority() );
           }
        }
    }
    class Demo3 
    {
        public static void main(String[] args) 
        {
            ThreadDemo1 th1 = new ThreadDemo1("线程1");
            ThreadDemo1 th2 = new ThreadDemo1("线程2");
            // 设置线程名
            th1.setName( "th1" );
            th2.setName( "th2" );
            // 设置线程优先级  1 ~ 10
            th1.setPriority( 10 ); 
            th2.setPriority( 7 ); 
            // 查看SUN定义的线程优先级范围
            System.out.println("max : " + Thread.MAX_PRIORITY );
            System.out.println("min : " + Thread.MIN_PRIORITY );
            System.out.println("nor : " + Thread.NORM_PRIORITY );
            th1.start();
            th2.start();
            System.out.println("Hello World!");
        }
    }

    练习:模拟卖票

    存在问题:这时候启动了四个线程,那么tickets是一个成员变量,也就是在一个线程对象中都维护了属于自己的tickets属性,那么就总共存在了四份。

    解决方案一:tickets使用staitc修饰,使每个线程对象都是共享一份属性。

    解决方案2编写一个类实现Runnable接口。

    author@nohert
  • 相关阅读:
    获取MySQL各版本yum源 并安装
    CentOS 防火墙实用操作
    简单3步将你的python转成exe格式
    java 实现扑克牌打印
    java 一维数组的总结笔记
    java中如何理解:其他类型 + string 与 自增类型转换和赋值类型转换
    c语言 0与非0
    Python中nonlocal的用法
    Python基础系列讲解-自动控制windows桌面
    flask_caching 缓存
  • 原文地址:https://www.cnblogs.com/gzgBlog/p/13598579.html
Copyright © 2011-2022 走看看