我使用synchronizedList()编写了以下代码:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package collectionsdemo;
import java.util.*;
class ThreadTest implements Runnable
{
Thread t;
private int var;
public ThreadTest(int var)
{
t = new Thread(this);
this.var = var;
t.start();
}
@Override
public void run()
{
System.out.println(var);
}
}
public class CollectionsDemo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws InterruptedException {
List<ThreadTest> synlist = Collections.synchronizedList(new ArrayList<>());
synlist.add(new ThreadTest(1));
synlist.add(new ThreadTest(2));
synlist.add(new ThreadTest(3));
synlist.add(new ThreadTest(4));
synlist.add(new ThreadTest(5));
for (int i = 0; i < 5; i++) {
synlist.get(i).t.join();
}
//System.out.println("Sunchronized list is :"+list);
}
}
现在,我仍然没有按照正确的顺序获得输出。它们每次都以不同的顺序出现。现在做什么?如何正确使用synchronizedList()方法?
答案 0 :(得分:0)
由于您在synchronizedList中添加了threadtest对象,因此所有对象都按照它们的顺序添加到列表中,因为它是一个列表,因为它是synchronizedList,它为您提供了额外的线程安全功能。
当你执行你的程序时,它会以不同的顺序打印数字,因为这个数字是由一个线程的treadtest类提供的,你无法通过这种方式控制线程的执行顺序。
但是为了确保添加的对象按自然顺序排列,您可以在ThreadTest类中添加getVar()方法并循环遍历列表并打印var值,您可以看到它的顺序相同;
class ThreadTest implements Runnable
{
Thread t;
private int var;
public ThreadTest(int var)
{
t = new Thread(this);
this.var = var;
t.start();
}
@Override
public void run()
{
System.out.println(var);
}
public int getVar(){
return var;
}
}
public class CollectionsDemo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws InterruptedException {
List<ThreadTest> synlist = Collections.synchronizedList(new ArrayList<>());
synlist.add(new ThreadTest(1));
synlist.add(new ThreadTest(2));
synlist.add(new ThreadTest(3));
synlist.add(new ThreadTest(4));
synlist.add(new ThreadTest(5));
for (int i = 0; i < 5; i++) {
synlist.get(i).t.join();
}
for(ThreadTest test :synlist){
System.out.println(test.getVar());
}
// System.out.println("Sunchronized list is :"+synlist);
}
}