1.生产者消费者测试的过程中使用了错误方法:Thread.currentThread().wait() 查了部分资料得出结论(如果不对的话烦请大佬指正): Thread.currentThread()方法获取当前线程对象,这时候是一个Thread对象,是不能够调用wait方法的,wait方法和notify方法均应有锁对象调用 wait方法和notify方法属于Object方法,Thread也属于Object对象,因此编译器对此错误不会报错 另外,Thread.currentThread().sout方法输出的结果为[main,5,main] 与之一一对应的是:[线程名称,线程优先级,线程组] 2.@Test方法和main方法的测试差异 :经测试发现,同样的生产消费死循环代码在@Test方法中只能运行一秒钟左右,其中一次测试结果如下:
而在main方法中测试则会一直执行,因此猜测:@Test方法对比main方法在防止内存泄露方面有更严格的策略;
但是另外测试:将while(true)循环内写为创建一个Object对象并打印内存地址,并不会发生上述现象。
TT1线程类中的run方法:
public void run() {
while (true){
synchronized (list){
if (list.size() == 0){
Object obj = new Object();
boolean add = list.add(obj);
System.out.println("1 -- >" + add);
list.notifyAll();
}else{
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
TT2中的run方法:
public void run() {
while (true) {
synchronized (list) {
if (list.size() > 0) {
Object remove = list.remove(0);
System.out.println("2 -- >" + remove);
list.notifyAll();
} else {
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
两者均有两段相同的代码:
private List list;
public TT2(List list) {
this.list = list;
}
测试类中的方法:
public void test01() throws ParseException {
List list = new ArrayList();
TT1 t11 = new TT1(list);
TT2 t22 = new TT2(list);
Thread t1 = new Thread(t11);
Thread t2 = new Thread(t22);
t1.start();
t2.start();
}