hadoop06---多线程

.1.1. 实现线程的两种方式

1、继承Thread方式

见代码MyThreadWithExtends

2声明实现 Runnable 接口的方式

见代码MyThreadWithImpliment

package cn.itcast_01_mythread.thread.testThread;

import java.util.Random;

public class MyThreadWithExtends extends Thread {
    String flag;
    float g = 1;
    
    public MyThreadWithExtends(String flag){
        this.flag = flag;
    }

    @Override
    public void run() {//并没有看出来线程1和线程2各自独有的。
        float f = 1;
        f++;//f是线程的值
        g++;//g是堆对象的值
        System.out.println("f:"+f);
        System.out.println("g:"+g);
        String tname = Thread.currentThread().getName();
        System.out.println(tname+"线程的run方法被调用……");
        Random random = new Random();
        for(int i=0;i<2;i++){
            try {
                Thread.sleep(random.nextInt(10)*100);
                System.out.println(tname+ "...."+ flag);//flag是堆对象的值,不同的线程和相同的线程来调用这个方法,都是对象里面的值。
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Thread thread1 = new MyThreadWithExtends("a");
        Thread thread2 = new MyThreadWithExtends("b");
        /*
        有独立的变量作用域。
        run方法是共用的,但是不同线程调的。
        f:2.0
        f:2.0
        g:2.0
        g:2.0
        Thread-1线程的run方法被调用……
        Thread-0线程的run方法被调用……
        Thread-0....a
        Thread-1....b
        Thread-0....a
        Thread-1....b
         */
//        thread1.start();
//        thread2.start();
        /**
                如果是调用thread的run方法,则只是一个普通的方法调用,不会开启新的线程
                都在主线程运行,所有的变量共享。thread1,thread2是2个堆中的变量。
            run方法是共用的,但是都是主线程调的。
            f:2.0
            g:2.0
            main线程的run方法被调用……
            main....a
            main....a
            f:2.0
            g:2.0
            main线程的run方法被调用……
            main....b
            main....b
         */
        thread1.run();
        thread2.run();
    }
}
package cn.itcast_01_mythread.thread.testThread;


public class MyThreadWithImpliment implements Runnable {
    int x;

    public MyThreadWithImpliment(int x) {
        this.x = x;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println("线程" + name + "的run方法被调用……");
        for (int i = 0; i < 10; i++) {
            System.out.println(x);
            try {
                Thread.sleep(100);
                
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new MyThreadWithImpliment(1), "thread-1");
        Thread thread2 = new Thread(new MyThreadWithImpliment(2), "thread-2");
//         thread1.start();
//         thread2.start();
        // 注意调用run和调用start的区别,直接调用run,则都运行在main线程中
        thread1.run();
        thread2.run();
    }
}
原文地址:https://www.cnblogs.com/yaowen/p/9006614.html