首页 / JAVA / 在Java中同步两个线程
在Java中同步两个线程
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在Java中同步两个线程,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2109字,纯文字阅读大概需要4分钟。
内容图文
![在Java中同步两个线程](/upload/InfoBanner/zyjiaocheng/660/9fc8511532a145f5bd36344c2e422e54.jpg)
我的java程序中有两个线程,一个是主线程,另一个是在主线程中生成的线程A.现在,我希望主线程启动线程A并等待,直到线程A在run方法中执行了部分代码,线程A应该挂起它自己.然后,主线程应该开始运行,运行几行代码,然后线程A应该再次从停止的地方开始,反之亦然.这应该发生n次.
我正在尝试如下:
线程A类:
public class ThreadA implements Runnable {
boolean suspended = false;
boolean stopped = false;
synchronized void stop() {
stopped = true;
suspended = false;
notify();
}
synchronized void suspend() {
suspended = true;
}
synchronized void resume() {
suspended = false;
notify();
}
void job() throws InterruptedException {
for (int i = 0; i < 5; i++)
synchronized (this) {
System.out.println("performing job.");
suspend();
while (suspended) {
notify();
suspended = false;
}
}
}
@Override
public void run() {
try {
job();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
主线程:
public class MainThread {
public static void main(String[] args) throws InterruptedException {
ThreadA a1=new ThreadA();
Thread t1=new Thread(a1);
synchronized (t1) {
t1.start();
for (int i = 0; i < 5; i++) {
t1.wait();
System.out.println("perform some action");
a1.resume();
}
}
}
}
预期产量:
performing job.
perform some action
performing job.
perform some action
performing job.
perform some action
performing job.
perform some action
performing job.
perform some action
实际输出:
performing job.
performing job.
performing job.
performing job.
performing job.
perform some action
我不知道为什么即使我在job方法中发出了notify()信号,整个for循环仍在线程A中执行.
解决方法:
这是更简化的方式
public class TwoThread {
public static void main(String[] args) throws InterruptedException {
ThreadA a1 = new ThreadA();
Thread t1 = new Thread(a1);
synchronized (a1) {
t1.start();
for (int i = 0; i < 5; i++) {
a1.wait();
System.out.println("perform some action " + i);
a1.notify();
}
}
}
}
public class ThreadA implements Runnable {
boolean suspended = false;
boolean stopped = false;
void job() throws InterruptedException {
for (int i = 0; i < 5; i++)
synchronized (this) {
System.out.println("performing job. " + i);
notify();
wait();
}
}
public void run() {
try {
job();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
内容总结
以上是互联网集市为您收集整理的在Java中同步两个线程全部内容,希望文章能够帮你解决在Java中同步两个线程所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。