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

  • 相关阅读:
    Codeforces 451A Game With Sticks
    POJ 3624 Charm Bracelet
    POJ 2127 Greatest Common Increasing Subsequence
    POJ 1458 Common Subsequence
    HDU 1087 Super Jumping! Jumping! Jumping!
    HDU 1698
    HDU 1754
    POJ 1724
    POJ 1201
    CSUOJ 1256
  • 原文地址:https://www.cnblogs.com/anpajin/p/6341219.html
Copyright © 2011-2022 走看看