所以我有一个代码:
public void runThreads(int number)
{
List<Thread> threadList = new ArrayList<Thread>();
for (int i = 0; i < number; i++)
{
Thread t = new MyThread(getRandomPerson(),i);
threadList.add(t);
}
for (Thread x : threadList)
{
x.start();
}
}
因此,我将线程添加到我的线程列表中,然后启动该线程。 这是 MyThread 类:
public class MyThread extends Thread
{
Person person;
int number;
public MyThread(Person person, int number)
{
this.person = person;
this.number = number;
}
@Override
public void run()
{
try
{
synchronized (this)
{
Thread.sleep(1000);
System.out.println(number + "\t" + person.getSurname());
Thread.sleep(1000);
System.out.println(number + "\t" + person.toString());
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
我想制作一个程序来创建线程,将它们添加到列表中,调用它们,但每个线程都应该等待,直到前一个线程结束其任务。 所以输出应该是这样的:
1 Surname
/** Waitning second */
1 person.toString()
/** Waiting second*/
And then the second thread start invoking:
2 Surname
....
如何使用synchronized
来实现这一点?我尝试了不同的方法来使用synchronized
,但失败了。
最佳答案
public class MyThread extends Thread
{
private static Object lock = new Object();
...
synchronized (lock)
{
Thread.sleep(1000);
System.out.println(number + "\t" + person.getSurname());
Thread.sleep(1000);
System.out.println(number + "\t" + person.toString());
}
...
这样你就可以按顺序得到同一个人的姓氏和 toString() 。您不会对人员执行严格的命令,人员 7 仍可能走在人员 1 之前。
关于java - 同步线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23472896/