昨天开始看《Java多线程编程核心技术》一书。记录一些所学:
1.通过查看“Windows资源管理器”中的列表,完全可以将运行在内存中的.exe文件理解成一个线程,线程是受操作系统管理的基本运行单元。
2.非线程安全:指多个线程对同一个对象中的同一个实例变量进行访问时会出现值被修改不同步的情况,进而影响程序的执行流程。
3.Thread.currentThread().interrupt() 用来停止一个线程,Thread.interrupted() Thred.isInterrupt() 查看线程是否停止。
package shi;
class MyThread extends Thread {
@Override
public void run() {
try {
for(int i = 0;i<50;i++) {
if (Thread.interrupted()) {
System.out.println("已经是停止状态!我要退出了");
throw new InterruptedException();
}
System.out.println(i);
}
System.out.println("我在for循环下面!");
}catch (InterruptedException e) {
System.out.println("进入MyThread类run方法中的catch了!");
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) {
MyThread thread = new MyThread();
try {
thread.start();
Thread.sleep(2000);
Thread.currentThread().interrupt();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("end!");
}
}