public
class
ThreadOnSpinWaitTest {
public
static
void main(
final
String args[]) throws InterruptedException {
final
NormalTask task1 =
new
NormalTask();
final
SpinWaitTask task2 =
new
SpinWaitTask();
final
Thread thread1 =
new
Thread(task1);
thread1.start();
final
Thread thread2 =
new
Thread(task2);
thread2.start();
new
Thread(() -> {
try
{
Thread.sleep(1000);
}
catch
(
final
InterruptedException e) {
e.printStackTrace();
} finally {
task1.start();
task2.sta*rt();
}
}).start();
thread1.join();
thread2.join();
}
private
<strong>
abstract
</strong>
static
class
Task
implements
Runnable {
volatile boolean canStart;
void start() {
this.canStart = true;
}
}
private
<strong>
static
</strong>
class
NormalTask
extends
Task {
<strong>@Override</strong>
public
void run() {
while
(!this.canStart) {
}
System.out.println(
"Done!"
);
}
}
private
<strong>
static
</strong>
class
SpinWaitTask
extends
Task {
<strong>@Override</strong>
public
void run() {
while
(!this.canStart) {
Thread.<strong>onSpinWait()</strong>;
}
System.out.println(
"Done!"
);
}
}
}