英文:
java synchronized fails to synchronize
问题
如何同步运行方法?
如果我在这里使用synchronized关键字,它不起作用。每次都会给我不同的输出?
class MyClass implements Runnable
{
boolean flag;
public MyClass(boolean val)
{
flag=val;
}
public synchronized void run()
{
long id=Thread.currentThread().getId();
int start=(flag)?1:2;
for(int i=start;i<=10;i+=2)
{
System.out.println("线程 "+id+" 输出:"+i);
}
}
}
public class Main {
public static void main(String[] args)
{
Thread t1=new Thread(new MyClass(false));
t1.start();
Thread t2=new Thread(new MyClass(true));
t2.start();
}
}
英文:
How do I synchronize the run method?
If I use the synchronized keyword here, it doesn't work. It gives me a different output every time?
class MyClass implements Runnable
{
boolean flag;
public MyClass(boolean val)
{
flag=val;
}
public synchronized void run()
{
long id=Thread.currentThread().getId();
int start=(flag)?1:2;
for(int i=start;i<=10;i+=2)
{
System.out.println("Thead "+id+" prints:"+i);
}
}
}
public class Main {
public static void main(String[] args)
{
Thread t1=new Thread(new MyClass(false));
t1.start();
Thread t2=new Thread(new MyClass(true));
t2.start();
}
}
答案1
得分: 2
每个线程都在使用不同的MyClass实例。如果在非静态实例上使用synchronized,这确保了该方法不会在同一MyClass实例的情况下被多个线程同时执行。如果要对所有MyClass实例进行同步,该方法必须是静态的。
class MyClass implements Runnable {
boolean flag;
public MyClass(boolean val)
{
flag=val;
}
private static synchronized void runTask(boolean flag) {
long id=Thread.currentThread().getId();
int start=(flag)?1:2;
for(int i=start;i<=10;i+=2)
{
System.out.println("线程 "+id+" 输出:"+i);
}
}
public void run()
{
runTask(flag);
}
}
英文:
Each thread is using a different instance of MyClass. If you use synchronized on a non static instance, this ensure the method is not executed by several threads at the same for the same MyClass instance. If you want to synchronize for all instances of MyClass, the method has to be static.
class MyClass implements Runnable {
boolean flag;
public MyClass(boolean val)
{
flag=val;
}
private static synchronized void runTask(boolean flag) {
long id=Thread.currentThread().getId();
int start=(flag)?1:2;
for(int i=start;i<=10;i+=2)
{
System.out.println("Thead "+id+" prints:"+i);
}
}
public void run()
{
runTask(flag);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论