[英]How to line break in java
I am using "\\n"
as a line break in Thread but it's not working. 我在线程中使用"\\n"
作为换行符,但无法正常工作。 I went through a lot of SO answers which suggest using System.getProperty("line.separator");
我经历了很多这样的答案,建议使用System.getProperty("line.separator");
but that also does not work for me.. 但这对我也不起作用。
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();
}
}
};
}
output is as follows: 输出如下:
1lock 2 acquired in thread thread-1 1lock 2 acquired in thread thread-0....
I would like it to be as follows: 我希望如下所示:
1lock 2 acquired in thread thread-1 1lock 2 acquired in thread thread-0....
Please use, System.getProperty("line.separator"); 请使用System.getProperty(“ line.separator”); like this, 像这样,
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());
您是否尝试将文本设置为"<html> this is <br> test</html>"
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.