您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Linux系统中,Java线程的唤醒主要涉及到线程同步和线程间通信
示例:
public class JavaThreadWakeup {
public static void main(String[] args) {
Object lock = new Object();
Thread t1 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 1: Holding the lock.");
try {
Thread.sleep(2000); // Sleep for 2 seconds to simulate some work.
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1: Releasing the lock.");
}
});
Thread t2 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 2: Waiting for the lock.");
try {
lock.wait(); // Wait for Thread 1 to release the lock.
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2: Holding the lock.");
}
});
t1.start();
t2.start();
}
}
示例:
public class JavaThreadWakeup {
public static void main(String[] args) {
final Object lock = new Object();
Thread t1 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 1: Holding the lock.");
try {
Thread.sleep(2000); // Sleep for 2 seconds to simulate some work.
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1: Notifying Thread 2.");
lock.notify(); // Notify Thread 2 to wake up.
}
});
Thread t2 = new Thread(() -> {
synchronized (lock) {
System.out.println("Thread 2: Waiting for the lock.");
try {
lock.wait(); // Wait for Thread 1 to notify.
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2: Holding the lock.");
}
});
t1.start();
t2.start();
}
}
在这两个示例中,我们使用了synchronized关键字和wait()、notify()方法来实现线程唤醒。请注意,这些方法必须在同步代码块或同步方法中使用,否则会抛出IllegalMonitorStateException异常。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。