public class MyThreadApp implements Runnable {
// produce
// consume
Thread produce = null;
Thread consume = null;
public void run() {
while (true) {
say();
}
}
/*
* synchronized 同步
* 只能有一个线程使用这个方法,别的线程都要等待
*/
public synchronized void say()
{
if (Thread.currentThread() == produce)
System.out.println("produce");
else if (Thread.currentThread() == consume)
System.out.println("consume");
else
System.out.println("main");
try {
Thread.sleep(600);
notifyAll(); //唤起所有的线程进行竞争。
} catch (InterruptedException e) {
}
}
public void go() {
produce = new Thread(this);
consume = new Thread(this);
produce.start();
consume.start();
}
public static void main(String[] args) {
System.out.println("main method started......");
MyThreadApp myThreadApp = new MyThreadApp();
myThreadApp.go();
myThreadApp.run();
System.out.println("gone!");
}
}
// produce
// consume
Thread produce = null;
Thread consume = null;
public void run() {
while (true) {
say();
}
}
/*
* synchronized 同步
* 只能有一个线程使用这个方法,别的线程都要等待
*/
public synchronized void say()
{
if (Thread.currentThread() == produce)
System.out.println("produce");
else if (Thread.currentThread() == consume)
System.out.println("consume");
else
System.out.println("main");
try {
Thread.sleep(600);
notifyAll(); //唤起所有的线程进行竞争。
} catch (InterruptedException e) {
}
}
public void go() {
produce = new Thread(this);
consume = new Thread(this);
produce.start();
consume.start();
}
public static void main(String[] args) {
System.out.println("main method started......");
MyThreadApp myThreadApp = new MyThreadApp();
myThreadApp.go();
myThreadApp.run();
System.out.println("gone!");
}
}
本文通过一个简单的Java程序示例介绍了线程同步的概念及其应用。程序中定义了一个实现Runnable接口的类MyThreadApp,该类通过synchronized关键字确保say()方法在同一时刻只能被一个线程调用。此外,通过notifyAll()方法来唤醒所有等待的线程以展示线程间的竞争。
1221

被折叠的 条评论
为什么被折叠?



