i--与System.out.println()多线程可能会出现线程安全问题
package com.company.javaThreadTest;
/**
* Created by likailong on 2016/10/24.
* 可能会出现非线程安全
* public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
虽然该方法内部用了同步 但是i--操作是在进入println之前
解决方法继续加同步
*/
public class Mythreadprintln extends Thread{
private int i=5;
public void run(){
System.out.println("i="+(i--)+"thread="+this.currentThread().getName());
}
public static void main(String [] args){
Mythreadprintln mythreadprintln=new Mythreadprintln();
Thread a=new Thread(mythreadprintln);
Thread b=new Thread(mythreadprintln);
Thread c=new Thread(mythreadprintln);
Thread d=new Thread(mythreadprintln);
Thread e=new Thread(mythreadprintln);
a.start();
b.start();
c.start();
d.start();
e.start();
}
}
模拟登陆出现的多线程问题
package com.company.javaThreadTest;
/**
* Created by likailong on 2016/10/24.
*
* 没有加同步
* username=bpassword=bb
username=bpassword=AA
加同步
username=apassword=AA
username=bpassword=bb
*/
public class MythreadServlet {
private static String usernamel;
private static String passwordl;
synchronized public static void doPsot(String username,String password){
try {
usernamel = username;
if (username.equals("a")){
Thread.sleep(1000);}
passwordl=password;
System.out.println("username="+usernamel+"password="+passwordl);
}catch (InterruptedException e){
e.printStackTrace();
}
}
private static class Alogin extends Thread{
public void run(){
MythreadServlet.doPsot("a","AA");
}
}
private static class Blogin extends Thread{
public void run(){
MythreadServlet.doPsot("b","bb");
}
}
public static void main(String [] args){
Alogin a=new Alogin();
a.start();
Blogin b=new Blogin();
b.start();
}
}