我在线程中使用"\n"
作为换行符,但它不起作用。我经历了很多建议使用的答案
System.getProperty("line.separator");
但这对我也不起作用..
public static void main(String args[]) {
final ReentrantLock lock1 = new ReentrantLock();
final ReentrantLock lock2 = new ReentrantLock();
Runnable try1_2 = getRunnable(lock1, "lock 1", lock2, "lock 2");
Runnable try2_1 = getRunnable(lock2, "lock 2", lock1, "lock 1");
new Thread(try1_2).start();
new Thread(try2_1).start();
}
private Runnable getRunnable(final ReentrantLock lock1, final String lock1Name, final ReentrantLock lock2, final String lock2Name) {
return new Runnable() {
@Override
public void run() {
try {
if (lock1.tryLock(1, TimeUnit.SECONDS)) {
System.out.println("1"+lock1Name + " acquired in thread " + Thread.currentThread().getName());
text_3.setText(text_3.getText() +"1"+lock1Name + " acquired in thread " + Thread.currentThread().getName());
if (lock2.tryLock(1, TimeUnit.SECONDS)) {
System.out.println("2"+lock2Name + " acquired in thread " + Thread.currentThread().getName());
text_3.setText(text_3.getText() + "\n"+"2"+lock2Name + " acquired in thread " + Thread.currentThread().getName());
Thread.sleep(2000);
} else {
System.out.println("3"+"Could not acquire "+lock2Name + " in thread " + Thread.currentThread().getName());
text_3.setText(text_3.getText() + "\n"+"3"+"Could not acquire "+lock2Name + " in thread " + Thread.currentThread().getName());
lock1.unlock();
System.out.println("4"+lock1Name + " released in thread " + Thread.currentThread());
text_3.setText(text_3.getText() + "\n"+"4"+lock1Name + " released in thread " + Thread.currentThread());
}
} else {
System.out.println("5"+"Could not acquire " + lock1Name + " in thread " + Thread.currentThread());
text_3.setText(text_3.getText() + "\n"+"5"+"Could not acquire " + lock1Name + " in thread " + Thread.currentThread());
}
} catch (InterruptedException e) {
} finally {
if (lock1.isHeldByCurrentThread()) lock1.unlock();
if (lock2.isHeldByCurrentThread()) lock2.unlock();
}
}
};
}
输出如下:
1lock 2 acquired in thread thread-1 1lock 2 acquired in thread thread-0....
我希望如下:
1lock 2 acquired in thread thread-1
1lock 2 acquired in thread thread-0....
答案 0 :(得分:3)
请使用,System.getProperty(“line.separator”);像这样,
String newLine = System.getProperty("line.separator");
//then insert newLine variable as this :
text_3.setText(text_3.getText() + newLine+ "2 " + lock2Name +
"acquired in thread " + Thread.currentThread().getName());
答案 1 :(得分:1)
您是否尝试将文字设为"<html> this is <br> test</html>"
?