标签:多线程
1.多线程概念 super(name);
}
@Override
public void run()
{
try
{
addThread.sleep(3000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
//给代码加锁
synchronized (xinXi1.class)
{
xinXi1.num++;
System.out.println(addThread.currentThread().getName()+"加法后="+xinXi1.num);
}
}
}
//减法子线程继承Thread
class subThread extends Thread{
public subThread(String name){
super(name);
}
@Override
public void run()
{
try
{
subThread.sleep(3000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
synchronized (xinXi1.class)
{
xinXi1.num--;
System.out.println(subThread.currentThread().getName()+"减法后="+xinXi1.num);
}
}
}
b.给方法加锁
例子:
public class xinXi1
{
public static int num = 11;
public static void main(String[] args)
{
System.out.println("num="+xinXi1.num);
addThread addThread = new addThread("线程1");
subThread subThread = new subThread("线程2");
addThread.start();
subThread.start();
}
//给方法加锁
public static synchronized void add(){
xinXi1.num++;
System.out.println(addThread.currentThread().getName()+"加法后="+xinXi1.num);
}
//给方法加锁
public static synchronized void sub(){
xinXi1.num--;
System.out.println(subThread.currentThread().getName()+"减法后="+xinXi1.num);
}
}
class addThread extends Thread{
public addThread(String name){br/>super(name);
}
@Override
public void run()
{
try
{
addThread.sleep(3000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
//线程里调用方法
xinXi1.add();
}
}
class subThread extends Thread{
public subThread(String name){br/>super(name);
}
@Override
public void run()
{
try
{
subThread.sleep(3000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
//线程里调用方法
xinXi1.sub();
}
}
注意事项:
1.synchronized(){}大括号里的代码就是加锁的代码,注意加锁会影响程序
的性能,除非涉及到多线程数据安全才需要加锁,其他情况建议不要加锁。
加锁的代码要尽量的少。
标签:多线程
原文地址:http://blog.51cto.com/13579083/2122674