1,Runable接口
实现Runable接口最终还是得用thread构造器构造一个线程、无论通过何种方式创建线程,最终都要依赖 Thread
类完成以下关键操作:
-
线程生命周期管理:启动(
start()
)、休眠(sleep()
)、中断(interrupt()
)等。 -
线程属性配置:名称、优先级、守护线程标志等。
因此,Runnable
仅定义任务逻辑,而 Thread
负责线程的创建和管理,二者分工明确。避免单继承限制
2,Thread.joint()
t1.start();
t1.join();
t2.start();
t1加入,让主线程等待
3.synchronized
设备数据采集与处理:在 MES 系统里,由于多个设备可能同时发送数据,若处理数据的代码没有进行同步控制,就可能出现数据冲突或不一致的情况。
生产任务调度:MES 系统需要对生产任务进行调度,例如分配任务给不同的设备或工人。在任务分配过程中,需要保证任务状态的一致性,避免多个调度线程同时对同一个任务进行分配,从而导致任务重复分配或状态混乱。
库存管理
public class Counter {
private int count = 0;
// 同步实例方法
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Count: " + counter.getCount());
}
}