多线程学习-- part 1 Thread

一.Thread的使用

(1)sleep:进程等一会

(2)join:让并发处理变成串行

(3)start:启动线程的唯一方法,start()首先为线程分配必须的系统资源,调度线程运行并执行线程的run()方法

(4)run:放入的是线程的工作

 

public class HelloWord {
    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                    System.out.println("我是子线程" + Thread.currentThread().getId());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("我是主线程" + Thread.currentThread().getId());
    }
}

 

(5)Interrupt 和stop:这两个关键字都是用来强制终止程序的

        终止线程的三种方法:

  1. Interrupt只管一次,相当于continue;
  2. stop相当于Break,线程直接退出,可能会产生不可预知的后果,不建议使用
  3. 利用共享变量标志位,在run()里面判断,是run()执行完自然退出
  4. run()不控制,执行完自己退出
public class HelloWord {
    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i < 3; i++) {
                    try {
                        Thread.sleep(5000);
                        System.out.println("我是子线程" + Thread.currentThread().getId());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
        t.interrupt();

        //这里开始Abort
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0; i < 3; i++) {
                    try {
                        Thread.sleep(5000);
                        System.out.println("我是子线程" + Thread.currentThread().getId());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        t1.start();
        t1.stop();

        System.out.println("我是主线程" + Thread.currentThread().getId());
    }

  

 

  线程的优点比较多,每个线程都需要默认的堆栈空间,所以说线程数受到内存空间大小的限制,如果线程数开得太多反而使得其反,进程被分配的时间片会被线程分得更细,就会导致处理器在不同线程频繁切换。 

 

posted @ 2017-05-23 11:11  jiguojing  阅读(336)  评论(0编辑  收藏  举报