多线程(一):认识线程,创建线程和线程的常用方法
概念
进程是系统分配资源的最小单位,线程是系统调度的最小单位。一个进程内的线程之间是可以共享资源的。每个进程至少有一个线程存在,即主线程。
例程:实现字符缓慢输出
public class ThreadDemo1 {
public static void main(String[] args) throws InterruptedException {
String content = "别人说你不行,是因为他自己做不到。你要尽全力保护你的梦想,那些嘲笑你的人,他们必定会失败," +
"他们想把你变成和他们一样的人。如果你有梦想的话,就要努力去实现, 就这样。";
for (char item : content.toCharArray()) {
System.out.print(item);
//执行到此行休眠200毫秒
Thread.sleep(200);
}
}
}
多线程的优势-增加运行速度
可以观察下面这个多线程例程,体验多线程时如何怎加运行速度的。
public class ThreadDemo2 {
//执行的循环次数
private static final Long count = 5_0000_0000L;
public static void main(String[] args) throws InterruptedException {
// System.out.println(Thread.currentThread().getName());
//调用多线程的方法
concorrency();
//调用单线程的方法
serial();
}
//单线程的方法
private static void serial() {
//记录开始时间
Long stime = System.currentTimeMillis();//记录当前时间的毫秒时间戳
// System.nanoTime();//当前时间的纳秒时间戳(更精确)
int a = 0;
//执行15亿次循环
for (int i = 0; i < 3 * count; i++) {
a++;
}
//记录结束时间
Long etime = System.currentTimeMillis();
System.out.println("单线程执行了: " + (etime - stime));
}
//多线程的方法
private static void concorrency() throws InterruptedException {
//开始时间
Long stime = System.currentTimeMillis();
//执行15亿次循环
//创建了线程任务
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
//具体业务
int a = 0;
for (int i = 0; i < count; i++) {
a++;
}
}
});
//开始执行线程
t1.start();
Thread t2 = new Thread(new Runnable()