package test;
public class test {
public void f1() {
new Thread() {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("f1");
}
}.start();
}
public void f2() {
new Thread() {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("f2");
}
}.start();
}
public void f3() {
new Thread() {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("f3");
}
}.start();
}
synchronized void m1() {
f1();
}
synchronized void m2() {
f2();
}
synchronized void m3() {
f3();
}
public static void main(String[] args) {
test test = new test();
test.m1();
test.m2();
test.m3();
}
}
多线程的执行和线程写的前后顺序无关,和CPU中的线程调度有关
多线程想要按照顺序执行,需要加入同步技术,默认情况是跟cpu占用资源时长有关
线程是没有执行顺序的, 哪个线程抢到执行权,就那个程序执行,其他线程等待。
虽然电脑看似可以执行多个程序,比如打开QQ、微信、浏览器等,但是电脑的cup依然是一个一个的再运行,只不过再这些程序中不停的切换,导致我们误以为是多后台运行。
所以配置电脑需要好的cup,这样运算速度很快,切换也就更快,最终电脑也就不卡顿。
package test;
public class test {
public void f1() {
new Thread() {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f1");
}
}.start();
}
public void f2() {
new Thread() {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f2");
}
}.start();
}
public void f3() {
new Thread() {
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("f3");
}
}.start();
}
synchronized void m1() {
System.out.println(1);
f1();
}
synchronized void m2() {
System.out.println(2);
f2();
}
synchronized void m3() {
System.out.println(3);
f3();
}
public static void main(String[] args) {
test test = new test();
test.m1();
test.m2();
test.m3();
}
}
可以发现1,2,3必定顺序打印。调用new Thread().start()才会创建新线程,在本文中的synchronized修饰的代码块其实是加锁执行的。也就是说实质上只是顺序创建了F1,F2,F3线程,但是线程的执行结果没有在主线程中保证