synchronized 同步方法不起作用 本帖最后由 AJrxin 于 2013-01-17 16:28:59 编辑 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 你的程序没让它起作用啊。synchronized锁定的是调用这个同步方法对象。也就是说,当一个对象P1在不同的线程中执行这个同步方法时,他们之间会形成互斥,达到同步的效果。public class ThreadTest { private String lock = "lock"; public ThreadTest() { ThreadClass threadClass = new ThreadClass(); Thread thread = new Thread(threadClass); thread.start(); } public static void main(String[] args) throws Exception { ThreadTest threadTest = new ThreadTest(); threadTest.abc(); } public synchronized void abc() { for (int i = 1; i < 1000; i++) { System.out.println("main thread run..." + ":" + i); } } class ThreadClass implements Runnable { public void run() { abc();// for (int i = 1; i < 1000; i++) {// System.out.println("thread run..." + ":" + i);// } } }} 谢谢楼上,如果想锁定方法,是不是要改为public void abc() { synchronized(lock){ for (int i = 1; i < 1000; i++) { System.out.println("main thread run..." + ":" + i); } } } synchronized 方法 = synchronized(this) netbeans界面设计,组件间距 new Object() 问题(不好意思,只能发100) 请教,谁详细讲解下netbean啊? one big question!!!!! ALL SCORES 关于图片的处理; 请问JComboBox如何只按一次回车就可以马上输出(附程序)。 jtable的selection事件响应问题 还望Java高人给小生一些启迪…… 加急,纠结,求代码大神将以下代码封装成公共函数的形式,然后供外界直接调用 谁懂遗传算法? 请在 “下面贴子” 与“本贴” 随便填个什么字,结贴,谢谢。 Swing 中 substance 设置水印的方法是什么?
synchronized锁定的是调用这个同步方法对象。也就是说,当一个对象P1在不同的线程中执行这个同步方法时,他们之间会形成互斥,达到同步的效果。
public class ThreadTest {
private String lock = "lock";
public ThreadTest() {
ThreadClass threadClass = new ThreadClass();
Thread thread = new Thread(threadClass);
thread.start();
} public static void main(String[] args) throws Exception {
ThreadTest threadTest = new ThreadTest();
threadTest.abc();
} public synchronized void abc() {
for (int i = 1; i < 1000; i++) {
System.out.println("main thread run..." + ":" + i);
}
} class ThreadClass implements Runnable { public void run() {
abc();
// for (int i = 1; i < 1000; i++) {
// System.out.println("thread run..." + ":" + i);
// }
}
}
}
public void abc() {
synchronized(lock){
for (int i = 1; i < 1000; i++) {
System.out.println("main thread run..." + ":" + i);
}
}
}