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

    利用Thread 类以及Runnable接口创建线程

    package javai;
    
    public class NewThread implements Runnable {
    
        Thread t;
    
        public NewThread() {
            t = new Thread(this, "I create a new thread.");
            System.out.println("Child thread:  " + t);
            t.start();
        }
    
        @Override
        public void run() {
    
            try {
                for (int i = 0; i < 5; i++) {
                    System.out.println("Chinld thead:  " + i);
                    Thread.sleep(500);
                }
            } catch (Exception e) {
                System.out.println("Child thead sinterrupted ");
            }
            finally {
                System.out.println("Child thead exiting ");
            }
        }
    
    }
    package javai;
    
    public class ThreadTest {
    
        public static void main(String[] args) {
            new NewThread();
    
            try {
                for (int i = 0; i < 5; i++) {
                    System.out.println("Main thead:  " + i);
                    Thread.sleep(500);
                }
            } catch (Exception e) {
                System.out.println("Main thead sinterrupted ");
            } finally {
                System.out.println("Main thead exiting ");
            }
        }
    }

    运行结果:

    Child thread: Thread[I create a new thread.,5,main]
    Main thead: 0
    Chinld thead: 0
    Chinld thead: 1
    Main thead: 1
    Main thead: 2
    Chinld thead: 2
    Main thead: 3
    Chinld thead: 3
    Main thead: 4
    Chinld thead: 4
    Main thead exiting
    Child thead exiting

  • 相关阅读:
    js关闭当前页面(窗口)的几种方式总结
    Servlet 文件上传
    Servlet Cookie 处理
    Servlet Session 跟踪
    Servlet 异常处理
    Servlet 编写过滤器
    Servlet HTTP 状态码
    Servlet 服务器 HTTP 响应
    Servlet 客户端 HTTP 请求
    Servlet 表单数据
  • 原文地址:https://www.cnblogs.com/anpajin/p/6341219.html
Copyright © 2011-2022 走看看