public class Sync {
public static void main(String[] args) {
Card c = new Card();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.run();
t2.run();
}
}class Card implements Runnable {
private int num = 0;
public void run() {
get();
}
private void get() {
num++;
try {
Thread.sleep(1000);
}catch(Exception e) {
System.out.println("error");
}
System.out.println("get " + num);
}
}
// output : get 1 get 2
为什么不是get 2 get 2 呢?
ps: 我的机器是双核的
public static void main(String[] args) {
Card c = new Card();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.run();
t2.run();
}
}class Card implements Runnable {
private int num = 0;
public void run() {
get();
}
private void get() {
num++;
try {
Thread.sleep(1000);
}catch(Exception e) {
System.out.println("error");
}
System.out.println("get " + num);
}
}
// output : get 1 get 2
为什么不是get 2 get 2 呢?
ps: 我的机器是双核的
线程要用start方法来启动,而不是直接调用run方法。
或者get 2 get 1
对单CPU来讲,要么先执行t1.run(),要么先执行t2.run()
双核同样是单CPU
他只不过是2个同时执行2样事情而已
单对单一的元素来说,还是一个cpu处理的
你写的不对
调用start()才是 告诉 jvm这是一个 线程方法要放到线程执行所以你的结果是:t1.run();//对象c的num=1 睡眠1000 不起作用
t2.run();//对象c的 num=2
所以答案就是get 1 get 2