java线程入门

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则表示调用的线程执行完后,再执行其他操作。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值