创建线程有两种方法
- 编写thread的子类,在类中覆写run方法。
- 编写实现Runnable接口的类,在类中覆写run方法,在使用的过程中将类的实例作为参数传递给Thread即可。
public class TestThread
{
public static void main(String args[]){
Out t = new Out();
t.start();
}
}
class Out extends Thread{ // thread的子类
public void run(){
System.out.println("this is a test!");
}
}
-------------------------------------------
public class TestThread
{
public static void main(String args[]){
Out t = new Out();
new Thread(t).start();
}
}
class Out implements Runnable{ //事项runnable接口
public void run(){
System.out.println("this is a test!");
}
}
- 多线程在运行过程中的并行,可能导致竞争某一资源导致相关的错误。ReentrantLocks类可以保护代码块。
import java.util.concurrent.locks.ReentrantLocks;
class Test implements Runnable{
ReentrantLock r = new Reentrantlock();
public void run(){
try{
r.lock();
dosomthing;
}finally{
r.unlock();
}
}
}
实例分析
银行多账户之间汇款
多余多账户之间的汇款,如果对于每一次的汇款过程都建立一个线程,这些线程之间将会出项资源竞争的问题,导致数据的出错,为了实现预期效果,线程之间应该设立对象的锁,以保证数据的正确性。
- 首先建立Bank类该类中应该包含资金传输的方法并将该方法sychronized申明隐式锁。在账户之间进行资金传输的的过程中不能被中断。
- 再建立相应的线程类,在类中建立bank类的对象,传递参数,调用传输方法
总结
对象锁的使用为了保证相应的过程不被中断,线程在过程中有相应的控制权。