Java两个线程交替运行示例,notify,wait用法,
话不多说,下面是代码示例
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private volatile Object mLock = new Object();
private volatile int mValue = 0;//多线程数据同步,使用volatile变量,数据立即写到主存中去
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread1 = new TestNotifyThread();
Thread thread2 = new TestNotifyThread();
thread1.setName("thread1");
thread2.setName("thread2");
thread1.start();
thread2.start();
}
public class TestNotifyThread extends Thread {
@Override
public void run() {
super.run();
while (mValue < 20) {
synchronized (mLock) {//获取锁
// Log.i(TAG, Thread.currentThread().getName() + " is coming");
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
mValue++;
Log.i(TAG, Thread.currentThread().getName() + " mValue = " + mValue);
mLock.notify();
try {
mLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized (mLock) {//这个最后调用下,以便所有线程退出
mLock.notifyAll();
}
Log.i(TAG, Thread.currentThread().getName() + " is out");
}
}
}
代码运行结果:
可看到thread1,与thread2交替运行。
以此类推,三个线程,四个纯程交替运行,怎样操作了??
答案是:两个线程创建了一个同步锁,三个线程交替运行得创建两个同步锁,四个线程交替运行得创建三个同步锁。
作者简介:https://shimo.im/docs/rp3OVwxle2fJn7Am/
上海徐汇
2022年6月26日