线程同时进行,为线程异步。 线程一个执行完结接着另一个线程执行叫做线程同步。
就想家里只有一个卫生间一样,不能两个人同时拉屎吧,把门锁好一个个来。 此时为线程同步。
班级表演舞蹈,同学们一起唱一起跳,叫做线程异步。
demo
actor 男演员和女演员 分别登台演出
package com.wenzewen.thread.demo.threadandrunnable;
/**
* Created with IntelliJ IDEA.
*
* @author: jhon
* @Date: 2019/4/20 on 8:18
* @description: 线程 Thead 和线程 runnerable
*/
public class Actor extends Thread {
@Override
public void run() {
boolean keepRunning = true;
int count = 0;
while (keepRunning) {
System.out.println(getName() + "登台演出");
System.out.println(getName() + "登台演出次数+" + (++count));
if (count == 100) {
keepRunning = false;
}
if (count % 10 == 0) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(getName() + "的演出结束了");
}
}
static class Actress implements Runnable {
@Override
public void run() {
boolean keepRunning = true;
int count = 0;
while (keepRunning) {
System.out.println(Thread.currentThread().getName() + "登台演出");
System.out.println(Thread.currentThread().getName() + "登台演出次数+" + (++count));
if (count == 100) {
keepRunning = false;
}
if (count % 10 == 0) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "的演出结束了");
}
}
}
public static void main(String[] args) {
Thread actor = new Actor();
actor.setName("Mr.thread");
actor.start();
Actress actress1 = new Actress();
Thread actress = new Thread(actress1, "Ms.runnerable");
actress.start();
}
}