java - 我要创建两个java线程(一个线程乘数另一个线程添加数字)
问题描述
我必须得到这样的输出:
这是我的代码。没有错误。PlusThread
它从第一行开始并打印。然后它会释放锁。之后MultiplyThread
开始运行。它将打印所有行而不是通知PlusThread
.
public class TestThread {
public static void main(String[] args) {
// TODO Auto-generated method stub
Object lock = new Object();
PlusThread pT = new PlusThread(lock, 2, 10);
pT.start();
MultiplyThread mT = new MultiplyThread(lock, 2, 10);
mT.start();
}
}
class PlusThread extends Thread {
Object lock;
int start, range;
public PlusThread(Object lock, int start, int range) {
super();
this.lock = lock;
this.start = start;
this.range = range;
}
@Override
public void run() {
synchronized (this) {
for (int i = start; i <= range; ++i) {
System.out.println(i + " + " + i + " = " + (i + i));
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
class MultiplyThread extends Thread {
Object lock;
int start, range;
public MultiplyThread(Object lock, int start, int range) {
this.lock = lock;
this.start = start;
this.range = range;
}
@Override
public void run() {
synchronized (this) {
for (int j = start; j <= range; ++j) {
System.out.println(j + " * " + j + " = " + (j * j));
this.notify();
}
}
}
}
这是我的输出:
解决方案
try this:
public class TestThread {
static Object lock = new Object();
public static void main(String[] args) {
// TODO Auto-generated method stub
PlusThread pT = new PlusThread(lock, 2, 10);
pT.start();
MultiplyThread mT = new MultiplyThread(lock, 2, 10);
mT.start();
}
}
class PlusThread extends Thread {
Object lock;
int start, range;
public PlusThread(Object lock, int start, int range) {
super();
this.lock = lock;
this.start = start;
this.range = range;
}
@Override
public void run() {
synchronized (lock) {
for (int i = start; i <= range; ++i) {
System.out.println(i + " + " + i + " = " + (i + i));
try {
lock.notify();
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
class MultiplyThread extends Thread {
Object lock;
int start, range;
public MultiplyThread(Object lock, int start, int range) {
this.lock = lock;
this.start = start;
this.range = range;
}
@Override
public void run() {
synchronized (lock) {
for (int j = start; j <= range; ++j) {
System.out.println(j + " * " + j + " = " + (j * j));
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
推荐阅读
- python - 如何复制 Tkinter 弹出窗口
- python - 基于比较删除excel中的行(python,pandas)
- apache-spark - PySpark 中的布尔索引是否得到官方支持?
- java - Flink Python 自定义连接器/源
- kubernetes - kubernetes nginx入口服务器片段注释未生效
- node.js - 强制在纱线之前运行 npm install ?
- php - PHP 正则表达式 url 匹配
- grep - Grep 获取范围内的数字
- javascript - nodejs获取视频持续时间
- airflow - 有新消息时气流中的 Sqs 传感器未触发