zoukankan      html  css  js  c++  java
  • Java多线程(一) Thread和 Runnable

    http://www.cnblogs.com/lwbqqyumidi/p/3804883.html

    1.继承Thread

    2.实现Runnable接口

       

    public class MyRunnable implements Runnable {
    
        @Override
        public void run() {
            // TODO Auto-generated method stub
          System.out.println("running..");
        }
    
    }
    public class Run {
        public static void main(String[] args) {
            Runnable runnable =new MyRunnable();
            Thread thread = new Thread(runnable);
            thread.start();
        }
    
    }

      如果同时继承Thread类实现Runnable接口,实际执行的Thread的run方法

    public class ThreadTest {
    
        public static void main(String[] args) {
            for (int i = 0; i < 100; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
                if (i == 30) {
                    Runnable myRunnable = new MyRunnable();
                    Thread thread = new MyThread(myRunnable);
                    thread.start();
                }
            }
        }
    }
    
    class MyRunnable implements Runnable {
        private int i = 0;
    
        @Override
        public void run() {
            System.out.println("in MyRunnable run");
            for (i = 0; i < 100; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
        }
    }
    
    class MyThread extends Thread {
    
        private int i = 0;
    
        public MyThread(Runnable runnable){
            super(runnable);
        }
    
        @Override
        public void run() {
            System.out.println("in MyThread run");
            for (i = 0; i < 100; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
        }
    }
  • 相关阅读:
    Palindrome Partitioning
    Minimum Path Sum
    Maximum Depth of Binary Tree
    Minimum Depth of Binary Tree
    Unique Binary Search Trees II
    Unique Binary Search Trees
    Merge Intervals
    Merge Sorted Array
    Unique Paths II
    C++ Primer Plus 笔记第九章
  • 原文地址:https://www.cnblogs.com/newlangwen/p/7551922.html
Copyright © 2011-2022 走看看