一、在使用suspend与resume方法时也容易出现因为方法的暂停而导致数据的不同步的情况。
public class SyschronizedObject {
private String username = "1";
private String password = "11";
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public void setValue(String username, String password) {
this.username = username;
if (Thread.currentThread().getName().equals("a")) {
System.out.println("a线程被暂停了");
Thread.currentThread().suspend();
}
System.out.println("进来了没?");
this.password = password;
}
public void printPassword(){
System.out.println("username= "+username +";password="+password);
}
}
public class TestMyThread {
public static void main(String[] args) {
final SyschronizedObject object = new SyschronizedObject();
try {
Thread myThread = new Thread(){
@Override
public void run() {
object.setValue("aa","a");
}
};
myThread.setName("a");
myThread.start();
Thread.sleep(5000);
Thread myThread2 = new Thread(){
@Override
public void run() {
object.printPassword();
}
};
myThread2.start();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main执行结束");
}
}
二、yield
yield的方法会放弃当前的CPU资源,让出时间片交给其他任务去执行,时间不固定,有可能刚刚放弃又马上获得CPU时间片。
public class MyThread extends Thread {
private long count = 5;
public MyThread() {
super();
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
@Override
public void run() {
long start = System.currentTimeMillis();
for (int i = 0; i < 500000; i++) {
//将时间片让给其他线程执行
Thread.yield();
count = count + (i + 1);
}
System.out.println("执行的时间是"+(System.currentTimeMillis() - start));
}
}
public class TestMyThread {
//
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
System.out.println("main执行结束");
}
}