多线程代码:
Test类
public class Test {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
Person x1 = new Person();
Person x2 = new Person();
ThreadPlus t1 = new ThreadPlus(x1);
ThreadPlus t2 = new ThreadPlus(x1);
t1.start();
t2.start();
System.out.println(x1.age);
}
}
Thread类
public class ThreadPlus extends Thread{
private Person m;
public ThreadPlus(Person x) {
m = x;
}
public void run() {
for(int i = 0; i < 10000; i++) {
m.age++;
}
}
}
Person类
public class Person {
public int age;
public String name;
public void m1() {
}
public void m2() {
m3();
}
public void m3() {
}
public static void m4() {
}
}
运行内存图:
大概率是主线程先执行sysout输出
如果想要t1、t2比主线程sysout先执行:
join 的意思是:等待当前线程任务执行完 再执行后面的。
但不会影响t1、t2的顺序,他们两个还是不能确定谁先执行
因为可能在进入就绪队列后,操作系统就将t1、t2线程分配给了cpu的核心去执行,也许在 join 起作用之前,某个线程就已经执行完了,所以t1、t2的顺序无法确定。
如果想要先执行t1,再执行t2:
start 表示线程进入就绪队列