1 并发编程介绍
一个Java程序运行在一个进程中,有时希望一个程序可以同时做多件事情,那么如果只有一个运算单元就明显不够,所以这时需要启动多个运算单元,这就是多线程。
多个线程的执行其实是抢占CPU的时间,但是感觉上好像在同时进行一样。
2 并发编程实战
为了使用多线程实现并发编程,我们可以提供如下三种做法。
a)Runnable任务
public class MyRunnable implements Runnable{
private int start;
private int end;
public MyRunnable(int start,int end){
this.start = start;
this.end = end;
}
@Override
public void run() {
int sum = 0;
for(int i=start;i<=end;i++){
sum+=i;
}
System.out.println(Thread.currentThread().getName()+"计算"+start+"到"+end+"的和为:"+sum);
}
}
public class Test {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable(1,100);
Thread thread1 = new Thread(myRunnable);
thread1.start();
Thread thread2 = new Thread(myRunnable);
thread2.start();
}
}
特点:比较灵活,可以同时继承父类,也可以实现多个接口,需要创建任务对象,创建线程对象,线程对象不可重用。
b)自定义Thread
public class MyThread extends Thread{
private int start;
private int end;
public MyThread(int start,int end){
this.start = start;
this.end = end;
}
@Override
public void run() {
int sum = 0;
for(int i=start;i<=end;i++){
sum+=i;
}
System.out.println(Thread.currentThread().getName()+"计算"+start+"到"+end+"的和为:"+sum);
}
}
public class Test {
public static void main(String[] args) {
MyThread myThread1 = new MyThread(1,100);
myThread1.start();
MyThread myThread2 = new MyThread(1,100);
myThread2.start();
}
}
特点:比较简单,不能再继承父类了,但可以实现多个接口,需要创建线程对象,线程对象不可重用。
c)线程池
public class MyRunnable implements Runnable{
private int start;
private int end;
public MyRunnable(int start,int end){
this.start = start;
this.end = end;
}
@Override
public void run() {
int sum = 0;
for(int i=start;i<=end;i++){
sum+=i;
}
System.out.println(Thread.currentThread().getName()+"计算"+start+"到"+end+"的和为:"+sum);
}
}
public class Test {
public static void main(String[] args) {
MyRunnable myRunnable1 = new MyRunnable(1,100);
MyRunnable myRunnable2 = new MyRunnable(1,100);
ExecutorService threadPool = Executors.newFixedThreadPool(2);
threadPool.submit(myRunnable1);
threadPool.submit(myRunnable2);
threadPool.shutdown();
}
}
特点:不需要创建线程对象,线程对象不可重用,提高程序运行效率,推荐使用。
|
|