java多线程,何时使用notify(),何时使用wait(),怎么使用synchronized
答:
0.ThreadLocal是为了保证各个线程间数据安全的,我们不需要任何同步代码,却能够保证我们线程间数据的安全。
1.使用synchronized 则根据锁进行同步,或是同步方法同步
2.在本线程执行完成逻辑后,调用notify通知其他线程准备执行
3.调用wait方法,将自己释放锁
以下是简单代码:
public class ThreadTest implements Runnable {
public ThreadTest() {
TestThread testthread1 = new TestThread(this, "1");
TestThread testthread2 = new TestThread(this, "2");
testthread2.start();
testthread1.start();
}
public static void main(String[] args) {
ThreadTest demoThread1 = new ThreadTest();
}
public void run() {
TestThread t = (TestThread) Thread.currentThread();
try {
if (!t.getName().equalsIgnoreCase("1")) {
synchronized (this) {
System.out.println(t.getName()+".wait() 将自己进入等待,释放锁");
wait();//wait将自己进入等待,释放锁
}
}
while (true) {
System.out.println(t.getName()+" in thread" + t.getName() + "="
+ t.increaseTime());
if (t.getTime() % 10 == 0) {
synchronized (this) {
System.out
.println("****************************************");
System.out.println(t.getName()+".notify() 通知正在等待的线程工作");
notify();
if (t.getTime() == 40)//end
break;
System.out.println(t.getName()+".wait() 将自己进入等待,释放锁");
wait();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class TestThread extends Thread {
private int time = 0;
public TestThread(Runnable r, String name) {
super(r, name);
}
public int getTime() {
return time;
}
public int increaseTime() {
return ++time;
}
}
join方法:join则表示调用的线程执行完后,再执行其他操作。