我有 A 类,我需要它来获取当前日期并修改它。
public class A {
private Calendar cal = Calendar.getInstance();
public void change() {
try
{
cal.add(Calendar.MONTH, 1);
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("Thread interrupted.");
}
}
public void print() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
System.out.println("Current Date Time : " + dateFormat.format(cal.getTime()));
}
}
在我的主函数中,我创建了类 A 的实例,并创建了两个线程:一个负责更改日期,另一个负责将其打印到控制台(使用 A 的打印和更改方法)
我想要它做的是在每次更改后打印新日期,但是我打印了相同的日期。
public class Main {
public static void main(String[] args) throws InterruptedException {
A a = new A();
Thread B = new Thread(new Runnable(){
public void run() {
for (int i = 0; i < 10; i++) {
a.print();
}
}
});
Thread C = new Thread(new Runnable(){
public void run(){
for(int i =0; i<10; i++) {
a.change();
}
}
});
synchronized (a) {
B.start();
C.start();
}
}
}
输出如下:
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
Current Date Time : 2019/12/29 18:27:27
最佳答案
这是您的代码的更新版本,它将适合您:
class A {
private BlockingQueue<Calendar> calList = new ArrayBlockingQueue<Calendar>(1);
public void change() {
try {
Calendar cal=Calendar.getInstance();
while(true) {
cal.add(Calendar.MONTH, 1);
calList.add(cal);
System.out.println("Adding month to date");
Thread.sleep(1000);
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
public void print() throws InterruptedException {
while(true) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
System.out.println("Current Date Time : " + dateFormat.format(calList.take().getTime()));
}
}}
目前,它继续循环并添加月份。您可以根据需要更改它:
public static void main(String[] args) throws InterruptedException {
A a = new A();
Thread B = new Thread(new Runnable() {
public void run() {
try {
a.print();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread C = new Thread(new Runnable() {
public void run() {
a.change();
}
});
B.start();
C.start();
}
关于java - 使用两个线程时如何在每次更改后打印值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59108469/