一个演示java中wait()和notify()方法的很好的小示例
有谁能给我一个很好的例子来演示java中wait()和notify()的功能吗。我尝试了下面的代码,但它没有显示我所期望的一个演示java中wait()和notify()方法的很好的小示例,java,multithreading,wait,notify,Java,Multithreading,Wait,Notify,有谁能给我一个很好的例子来演示java中wait()和notify()的功能吗。我尝试了下面的代码,但它没有显示我所期望的 public class WaitDemo { int i = 10; int display() { System.out.println("Lexmark"); i++; return i; } } 问题是类WaitDemo中的方法没有得到执行,根据我的想法,SOP after wait()应该
public class WaitDemo {
int i = 10;
int display() {
System.out.println("Lexmark");
i++;
return i;
}
}
问题是类WaitDemo中的方法没有得到执行,根据我的想法,SOP after wait()应该执行。请帮我解决这个问题。您的
try
块中有两级大括号{
。如果您删除了内部大括号集(看起来没有任何作用),是否解决了问题
这里有几个例子,所有这些都说明了它的用途。最后一个链接是一组可以帮助您解决问题的结果。如果您需要更具体的东西,请告诉我您的应用程序正在尝试做什么,我可以尝试找到更具体到您的情况的例子
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* @author sbarnum
*/
public class WorkerPauseManagerTest {
public static void main(String[] args) {
final WorkerPauseManager pauseManager = new WorkerPauseManager();
new Worker("Worker 1", pauseManager).start();
new Worker("Worker 2", pauseManager).start();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JToggleButton playPauseButton = new JToggleButton(new AbstractAction("Pause") {
public void actionPerformed(final ActionEvent e) {
JToggleButton source = (JToggleButton) e.getSource();
if (source.isSelected()) {
pauseManager.start();
source.setText("Pause");
} else {
pauseManager.pause();
source.setText("Play");
}
}
});
playPauseButton.setSelected(true); // already running
JOptionPane.showMessageDialog(null, playPauseButton, "WorkerPauseManager Demo", JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
});
}
private static class Worker extends Thread {
final String name;
final WorkerPauseManager pauseManager;
public Worker(final String name, final WorkerPauseManager pauseManager) {
this.name = name;
this.pauseManager = pauseManager;
}
@Override
public void run() {
while (!Thread.interrupted()) {
try {
pauseManager.pauseIfNeeded();
System.out.println(name + " is running");
Thread.sleep(1000L);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public static final class WorkerPauseManager {
private boolean paused;
public synchronized void pauseIfNeeded() throws InterruptedException {
if (paused) wait();
}
public synchronized void pause() {
this.paused = true;
}
public synchronized void start() {
this.paused = false;
notifyAll();
}
}
}
下面是Object类中wait¬ify的一个示例。客户试图提取价值2000的货币,但该帐户只有1000,因此必须等待存款。一旦存款,客户将能够提取金额。在存款之前,客户将等待
class Cust {
private int totalAmount = 1000;
public synchronized void withdrawal(int amount) {
System.out.println("Total amount " + totalAmount + " withdrawing amount " + amount);
while (this.totalAmount < amount) {
System.out.println("not enough amount..waiting for deposit..");
try { wait(); } catch (Exception e) {}
}
this.totalAmount -= amount;
System.out.println("Withdrawal successful.. Remaining balance is "+totalAmount);
}
public synchronized void deposit(int amount){
System.out.println("Depositing amount "+amount);
this.totalAmount += amount;
System.out.println("deposit completed...and Now totalAmount is " + this.totalAmount);
notify();
}
}
class Depo implements Runnable {
Cust c; int depo;
Depo(Cust c, int depo){
this.c = c;
this.depo = depo;
}
@Override
public void run() {
c.deposit(depo);
}
}
class Withdrawal implements Runnable {
Cust c; int with;
Withdrawal(Cust c, int with){
this.c = c;
this.with = with;
}
@Override
public void run() {
c.withdrawal(with);
}
}
public class ObjectWaitExample {
public static void main(String[] args) {
Cust c = new Cust();
Thread w = new Thread(new Withdrawal(c, 2000));
Thread d1 = new Thread(new Depo(c, 50));
Thread d2 = new Thread(new Depo(c, 150));
Thread d3 = new Thread(new Depo(c, 900));
w.start();
d1.start();
d2.start();
d3.start();
}
}
类客户{
私人整数总额=1000;
公共同步作废取款(整笔金额){
系统输出打印项次(“总金额”+总金额+“提取金额”+金额);
while(this.totalAmount
我创建了两个线程,一个用于打印奇数(OddThread),另一个用于打印偶数(EvenThread)。在每个线程的run方法中,我使用Print类的共享对象调用printOdd()和Print偶数()分别针对奇数和EventThread。我将Print的共享对象设置为静态,以便只生成一个副本。现在在Print对象上同步时,我使用了一个布尔标志,这样当奇数线程打印奇数时,它将被发送到等待状态,同时通知偶数线程执行。写入逻辑以这样一种方式,奇数线程将始终首先打印奇数,无论发生什么情况,因为该标志最初设置为false,以防止偶数线程执行并将其发送到等待状态
package com.amardeep.test;
public class ThreadDemo {
// Shared object
static Print print = new Print();
public static void main(String[] args) {
new Thread(new OddThread()).start();
new Thread(new EvenThread()).start();
}
}
class EvenThread implements Runnable {
@Override
public void run() {
ThreadDemo.print.printEven();
}
}
class OddThread implements Runnable {
@Override
public void run() {
ThreadDemo.print.printOdd();
}
}
class Print {
public volatile boolean flag = false;
public synchronized void printEven() {
for (int i = 1; i <= 10; i++) {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
if (i % 2 == 0) {
System.out.println("from even " + i);
flag = false;
notifyAll();
}
}
}
}
public synchronized void printOdd() {
for (int i = 1; i <= 10; i++) {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
if (i % 2 != 0) {
System.out.println("from odd " + i);
flag = true;
notifyAll();
}
}
}
}
}
output:-
from odd 1
from even 2
from odd 3
from even 4
from odd 5
from even 6
from odd 7
from even 8
from odd 9
from even 10
package com.amardeep.test;
公共类线程演示{
//共享对象
静态打印=新打印();
公共静态void main(字符串[]args){
新线程(new OddThread()).start();
新线程(neweventhread()).start();
}
}
类EvenThread实现Runnable{
@凌驾
公开募捐{
ThreadDemo.print.printfeen();
}
}
类OddThread实现Runnable{
@凌驾
公开募捐{
ThreadDemo.print.printOdd();
}
}
类打印{
public volatile boolean标志=false;
公共同步的void print偶数(){
对于(inti=1;iwait方法,当某个线程通过锁定某个对象执行同步块时(我们
class Cust {
private int totalAmount = 1000;
public synchronized void withdrawal(int amount) {
System.out.println("Total amount " + totalAmount + " withdrawing amount " + amount);
while (this.totalAmount < amount) {
System.out.println("not enough amount..waiting for deposit..");
try { wait(); } catch (Exception e) {}
}
this.totalAmount -= amount;
System.out.println("Withdrawal successful.. Remaining balance is "+totalAmount);
}
public synchronized void deposit(int amount){
System.out.println("Depositing amount "+amount);
this.totalAmount += amount;
System.out.println("deposit completed...and Now totalAmount is " + this.totalAmount);
notify();
}
}
class Depo implements Runnable {
Cust c; int depo;
Depo(Cust c, int depo){
this.c = c;
this.depo = depo;
}
@Override
public void run() {
c.deposit(depo);
}
}
class Withdrawal implements Runnable {
Cust c; int with;
Withdrawal(Cust c, int with){
this.c = c;
this.with = with;
}
@Override
public void run() {
c.withdrawal(with);
}
}
public class ObjectWaitExample {
public static void main(String[] args) {
Cust c = new Cust();
Thread w = new Thread(new Withdrawal(c, 2000));
Thread d1 = new Thread(new Depo(c, 50));
Thread d2 = new Thread(new Depo(c, 150));
Thread d3 = new Thread(new Depo(c, 900));
w.start();
d1.start();
d2.start();
d3.start();
}
}
package com.amardeep.test;
public class ThreadDemo {
// Shared object
static Print print = new Print();
public static void main(String[] args) {
new Thread(new OddThread()).start();
new Thread(new EvenThread()).start();
}
}
class EvenThread implements Runnable {
@Override
public void run() {
ThreadDemo.print.printEven();
}
}
class OddThread implements Runnable {
@Override
public void run() {
ThreadDemo.print.printOdd();
}
}
class Print {
public volatile boolean flag = false;
public synchronized void printEven() {
for (int i = 1; i <= 10; i++) {
if (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
if (i % 2 == 0) {
System.out.println("from even " + i);
flag = false;
notifyAll();
}
}
}
}
public synchronized void printOdd() {
for (int i = 1; i <= 10; i++) {
if (flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
if (i % 2 != 0) {
System.out.println("from odd " + i);
flag = true;
notifyAll();
}
}
}
}
}
output:-
from odd 1
from even 2
from odd 3
from even 4
from odd 5
from even 6
from odd 7
from even 8
from odd 9
from even 10
A a = new A (); // some class object call "a"
synchronized (a){
a.wait ();//exceptions must be handled
}
a.notify ()