社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
进程 | 线程 |
---|---|
地址空间、全局变量、打开的文件 | 程序计数器 |
子进程 | 寄存器、堆栈 |
账户信息 | 状态 |
进程维护一个数据结构:包含进程所必须的先关资源(进程控制块)
线程:内核态、用户态、混合使用
Cooperative Threads-Scheduling:程序自主控制
Preemptive Threads-Scheduling:优先级队列
implements Runnable
public class LiftOff implements Runnable {
protected int countDown = 10; //Default
private static int taskCount = 0;
private final int id = taskCount++;
public LiftOff(){}
public LiftOff(int countDown) {
this.countDown = countDown;
}
public String status() {
return "#" + id + "(" +
(countDown > 0 ? countDown : "Liftoff!") + ").";
}
@Override
public void run() {
while(countDown-- > 0) {
System.out.print(status());
Thread.yield();
}
System.out.println(id);
}
}
new Thread(Runnable object).start()
执行任务。由线程调度器调度执行。public final static void main(String[] args) {
//new LiftOff().run(); // 通过方法在一个线程内调用
for(int i = 0; i < 5; i++) {
new Thread(new LiftOff()).start();
}
System.out.println("Waiting for LiftOff.");
}
public static final void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
//Executors.newFixedThreadPool(5);
//Executors.newSingleThreadExecutor();
for(int i=0; i<5; i++) {
exec.execute(new LiftOff());
}
exec.shutdown();
System.out.println("Waiting for LiftOff.");
}
implements Callable<T>
Thread.sleep(100);TimeUnit.MILLISECONDS.sleep(100);
yield
synchronized
、显示灵活的加锁Lock:new ReentrantLock()
对象volatitle
变量和同步加锁AtomicInteger, AtomicLong, AtomicReference
synchronized(this)
对象同步代码块synchronized(object)
wait,notify,notifyAll
synchronized
——同步代码块、方法。内置锁的可重入性。//解决并发编程的方案
1、不在线程之间共享该状态变量
2、将状态变量修改为不可变的变量
3、在访问状态变量时使用同步锁
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!