zoukankan      html  css  js  c++  java
  • java 线程Thread 技术--创建线程的方式

    在第一节中,对线程的创建我们通过看文档,得知线程的创建有两种方式进行实现,我们进行第一种方式的创建,通过继承Thread 类 ,并且重写它的run

    方法,就可以进行线程的创建,所有的程序执行都放在了run 方法里;可以说run 方法里放入的是线程执行的程序;在执行线程的时候,需要调用线程的start

    方法,就可以进行线程的启动;

      总之就是:代码写在run 方法里面,但是线程的执行调用start 方法,start 方法会开启一个线程去执行run 方法;

    方式-:

    public class ThreadCreatMethod1 {
        
        //thread start ,must be invoke start method to start thread
        
        
        public static void main(String[] args) {
            ExtendRunnable thread =new ExtendRunnable();
            thread.start();
        }
        
    }
    
    /**
     * 
     * Note:
     * Thread create method 1:
     * 1.extends Thread Class
     * 2.override run method
     * 
     * @author iscys
     *
     */
    class ExtendRunnable extends Thread{
        
        
        @Override
        public void run() {
            
            for(int i=0;i<100;i++) {
                
                System.out.println("thread excute result"+Thread.currentThread().getName()+"..."+i);
            }
            
            
        }
        
    } 

    方式二:

      通过创建实现runnable 接口,实现它的run 方法的类,并将此类传递给线程,执行start 方法

    public class ThreadCreatMethod2 {
    
        //pass implement runnable class in thread construct
        public static void main(String[] args) {
            
            Thread th =new Thread(new ImplementRunnable());
            
            th.start();
        }
        
    }
        
        /**
         * Thread create method 2
         * 1.implements interface Runnable
         * 2.achieve run method
         * 
         */
        
        class ImplementRunnable implements Runnable{
    
            @Override
            public void run() {
                
                for(int i=0;i<100;i++)
                System.out.println("implement runnable method"+Thread.currentThread().getName()+"..."+i);
                
            }
    
    }
    原创打造,多多指教
  • 相关阅读:
    jpa项目倒入eclipse中,无法识别注解的实体类
    上传文件的js控件,无刷新
    Maven 安装
    location 浅解析
    小程序 上传图片(多张、多次上传),预览图片 删除图片
    小程序 跳转问题 (来源见注明)
    GIT 安装和升级
    span 不使用float 靠右对齐且垂直居中
    PHP 根据php传的值修改 select 中动态生成的 option 组的默认选中值
    MAC 隐藏功能
  • 原文地址:https://www.cnblogs.com/iscys/p/9704270.html
Copyright © 2011-2022 走看看