Java多线程的优点:
(1)它不会阻塞用户,因为线程是独立的,可以同时执行多个操作。
(2)可以一起执行许多操作,因此可以节省时间。
(3)线程是独立的,因此如果在单个线程中发生异常,它不会影响其他线程
Java的多任务处理:
多任务处理是同时执行多个任务的过程。使用多任务来利用CPU,多任务处理可以通过两种方式实现:
多进程 多线程
基于进程的多任务处理(多进程)
- 每个进程在内存中都有一个地址。 换句话说,每个进程分配一个单独的内存区域。
- 进程是重量级的。
- 进程之间的通信成本很高。
- 从一个进程切换到另一个进程需要一些时间来保存和加载寄存器,内存映射,更新列表等。
基于线程的多任务处理(多线程)
- 线程共享相同的地址空间。
- 线程是轻量级的。
- 线程之间的通信成本很低
使用多线程:
继承Thread类 实现Runnable接口
currentThread()方法:返回代码段正在被哪个线程调用的信息;
isAlive()方法:判断当前线程是否处于活动状态;
sleep()方法:在指定的毫秒数内让当前正在执行的线程休眠;
getId()方法:取得线程的唯一标识;
interrupted()方法:测试当前线程是否已经中断(会执行中断操作);
isInterrupted()方法:测试线程是否已经中断(只测试);
public class MyThreadSp extends Thread{
public void run() {
super.run();
try {
System.out.println("run begin");
Thread.sleep(200000);
System.out.println("run end");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("在沉睡中被停止,进入catch " + this.isInterrupted());
e.printStackTrace();
}
}
}
public class RunSp {
public static void main(String[] args) {
try {
MyThreadSp thread = new MyThreadSp();
thread.start();
Thread.sleep(200);
thread.interrupt();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end!");
}
}
synchronized
同步修辞符;可以保证多个进程执行操作同一变量时确定同步;
public class LoginServlet {
private static String usernameRef;
private static String passwordRef;
synchronized public static void doPost(String username, String password) {
try {
usernameRef = username;
if (username.equals("a")) {
Thread.sleep(5000);
}
passwordRef = password;
System.out.println("username= " + usernameRef + " password=" + password);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
stop()方法,暴力停止;已被弃用
suspend() resume()暂停和恢复;缺点 独占 不同步;已被弃用
yield()方法,放弃当前CPU资源,让给其他任务
setPrority()方法,改变优先级;CPU尽量将执行资源给优先级比较高的线程
(高优先级的线程总是大部分先执行完,不代表高优先级的线程全部先执行完)
(程序优先级和打印顺序无关,它们的关系具有不确定性和随机性)
import java.util.Random;
public class MyThreadP5 extends Thread{
public void run() {
long beginTime = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
Random random = new Random();
random.nextInt();
}
long endTime = System.currentTimeMillis();
System.out.println(" -------Thread5 use time = " + (endTime - beginTime));
}
}
import java.util.Random;
public class MyThreadP6 extends Thread{
public void run() {
long beginTime = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
Random random = new Random();
random.nextInt();
}
long endTime = System.currentTimeMillis();
System.out.println(" +++++++Thread6 use time = " + (endTime - beginTime));
}
}
public class RunP56 {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
MyThreadP5 thread5 = new MyThreadP5();
thread5.setPriority(5);
MyThreadP6 thread6 = new MyThreadP6();
thread6.setPriority(6);
thread5.start();
thread6.start();
}
}
}