Java多线程顺序执行
可恶的Java多线程,一直没搞懂同步的作用!
一直以为同步的时候只要锁住对象就能顺序执行了:
[java]
public class Test {
final static byte[] b = new byte[0];
public static void main(String[] args) {
Test t = new Test();
t.thread.start();
Test t2 = new Test();
t2.thread.start();
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
test();
}
});
public void test() {
synchronized (this) {
for (int n = 0; n < 100; n++) {
System.out.println(thread.getName() + ":" + n);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Test {
final static byte[] b = new byte[0];
public static void main(String[] args) {
Test t = new Test();
t.thread.start();
Test t2 = new Test();
t2.thread.start();
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
test();
}
});
public void test() {
synchronized (this) {
for (int n = 0; n < 100; n++) {
System.out.println(thread.getName() + ":" + n);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
但是这样是错误的!两个线程还是交替执行!
查阅了很多资料才知道上面这个锁是不正确的,两个线程锁住的this对象不是同一个,所以导致交叉执行。应该修改为:
[java]
public class Test {
final static byte[] b = new byte[0];
public static void main(String[] args) {
Test t = new Test();
t.thread.start();
t.test();
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
test();
}
});
public void test() {
synchronized (this) {
for (int n = 0; n < 100; n++) {
System.out.println(thread.getName() + ":" + n);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Test {
final static byte[] b = new byte[0];
public static void main(String[] args) {
Test t = new Test();
t.thread.start();
t.test();
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
test();
}
});
public void test() {
synchronized (this) {
for (int n = 0; n < 100; n++) {
System.out.println(thread.getName() + ":" + n);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
补充:软件开发 , Java ,