Java并发编程(一) —— 线程

Java的线程机制是抢占式的,所谓的抢占式指的是每一个线程都会被分配一个指定大小的时间片,一旦这个时间片用完,就会通过上下文切换到另一个线程上去。
并发是主要是为了提高单处理器的性能。创建一个线程会有上下文切换和线程创建的消耗,那为什么要不只用串行呢?因为要考虑到阻塞这一个情况,一旦使用串行,某一项任务产生了阻塞,那么后面的任务都无法开展。
通常函数式语言能做到并发任务彼此隔离。
在线程这个层面上,系统又分为协作式系统和抢占式系统。

线程创建

继承Thread实现多线程

实现Runnable接口实现多线程

使用Callable实现多线程

使用Callable实现,相比于继承Thread类和实现Runnable接口,它的不同之处在于可以在任务结束的时候返回一个值。使用方法:
实现Runnable接口,覆写call方法。调用ExecutorService对象的submit方法,返回来的对象要放在Future中,如返回的是String,则Future
调用get即可获得线程结束时返回的值

public class ThreadTest4 {
	
	public static void main(String[] args) {
		ExecutorService exec = Executors.newCachedThreadPool();
		Future<String> result = exec.submit(new MyThread());
		for(int i = 0;i<1000;i++){
			System.out.println("main");
		}
		try {
			System.out.println(result.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		
	}

}

class MyThread implements Callable<String>{

	

	@Override
	public String call() throws Exception {
		for(int i = 0;i<1000;i++){
			System.out.println("test");
		}
		return "任务完成";
	}
}

start()与run()

run方法相当于一次普通的方法调用,并不会创建线程。

public class CreateThread {

    static class Test implements Runnable{

        @Override
        public void run() {
            System.out.println("test");
        }
    }

    public static void main(String[] args) {
        new Thread(new Test()).run();
    }

}

执行后使用线程快照,发现只有一个main线程

如果改成start,则会成功创建线程。

线程停止

终止线程的几种方式:

  • 线程正常退出,也就是run方法执行完
  • 使用stop方法强行终止,不推荐
  • 使用interrupt方法中断线程

interrupt 终止线程

public class ThreadDemo {

    public static void main(String[] args) throws InterruptedException {
        MyThread myThread = new MyThread();
        myThread.start();
        TimeUnit.SECONDS.sleep(5L);
        myThread.interrupt();

    }

}

class MyThread extends Thread {

    @Override
    public void run() {
        super.run();
        for (int i = 0; ; i++) {
            System.out.println(this.isInterrupted());
            if (this.isInterrupted()) {
                System.out.println("线程终止");
                break;
            }
            System.out.println(i);
            try {
                TimeUnit.SECONDS.sleep(2L);
            } catch (InterruptedException e) {
                e.printStackTrace();
                this.interrupt();
            }
            System.out.println("test----------");
        }
    }
}

运行结果

线程休眠

Thread.sleep()是Thread类的一个静态方法,使当前线程休眠,进入阻塞状态(暂停执行),如果线程在睡眠状态被中断,将会抛出IterruptedException中断异常。

sleep(0)

放弃当前线程的时间片,将CPU时间片让给优先级高于或等于当前线程的其他线程。

参考文档

《Java编程思想》

posted @ 2016-09-21 23:40  清泉白石  阅读(211)  评论(0编辑  收藏  举报