java之并发

一、线程

  在java中多线程执行任务,主要有两种方式,一种是通过继承Thread类,重写run方法,优点是比较方便的创建一个线程,缺点是java中每个类只能有一个基类,所有继承了T火热ad类后,就不能再继承其他类了;第二种是实现Runnable接口,实现接口中的run方法,然后把类的对象交给Thread构造器,或者添加到执行器Executor中。

 1 class MyThread extends Thread {
 2     public void run() {
 3         while(!Thread.interrupted()) {
 4             System.out.println(this);
 5         }
 6     }
 7 }
 8 
 9 class MyTask implements Runnable {
10     public void run() {
11         while (!Thread.interrupted()) {            
12             int x = 0;
13             for (int i = 0; i < 1000000; ++i) {
14                 x += 5*i;
15             }                
16         }
17     }
18 }
19 
20 
21 public class InterruptTest {
22 
23     public static void main(String[] args) {
24         // TODO Auto-generated method stub
25         Thread t = new Thread(new MyTask());
26         t.start();
27         t.interrupt();
28         
29         MyThread t2 = new MyThread();
30         t2.start();
31     }
32 }

 

posted on 2016-01-13 11:19  冰雨纷飞  阅读(245)  评论(0编辑  收藏  举报

导航