-------
android培训、
java培训、期待与您交流! ----------
多线程:
实现多线程的方式有两种:
1,继承Thread类,重写run()方法,新建子类对象,调用start()方法开启线程,
class T extend Thread()
{
public void run()
{
for(int i=0;i++;i<100)
{
system.out.println(this.getName()+" "+i);
}
}
}
class test
{
public static void main(String[] args)
{
T t1 = new T ();
T t2 = newT ();
t1.start();
t2.start();
}
}
2.实现Runable接口,重写run()方法,新建子类对象,new Thread 类 将子类对象作为参数传进去
class T implements Thread()
{
public void run()
{
for(int i=0;i++;i<100)
{
system.out.println(this.getName()+" "+i);
}
}
}
class test
{
public static void main(String[] args)
{
Thread t1 = new Thread(new T() );
Thread t2 = new Thread(new T() );
t1.start();
t2.start();
}
}
线程同步的方法有:
将要共同执行的语句放进
sysnchroinzed(任意对象)
{
}
语句块中,或者在方法上加上synchronized修饰符
创建lock对象,使用lock.lock()方法进行加锁,我们要在创建一个Condition 对象作为这个锁的监听器
比如:
class BoundedBuffer {
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void put(Object x) throws InterruptedException {
lock.lock(); //上锁
try {
condition.await(); //使线程处于等待状态
方法体;
condition.signal(); // 唤醒线程
} finally {
lock.unlock(); //释放锁
}
}
实现多线程的方式有两种:
1,继承Thread类,重写run()方法,新建子类对象,调用start()方法开启线程,
class T extend Thread()
{
public void run()
{
for(int i=0;i++;i<100)
{
system.out.println(this.getName()+" "+i);
}
}
}
class test
{
public static void main(String[] args)
{
T t1 = new T ();
T t2 = newT ();
t1.start();
t2.start();
}
}
2.实现Runable接口,重写run()方法,新建子类对象,new Thread 类 将子类对象作为参数传进去
class T implements Thread()
{
public void run()
{
for(int i=0;i++;i<100)
{
system.out.println(this.getName()+" "+i);
}
}
}
class test
{
public static void main(String[] args)
{
Thread t1 = new Thread(new T() );
Thread t2 = new Thread(new T() );
t1.start();
t2.start();
}
}
线程同步的方法有:
将要共同执行的语句放进
sysnchroinzed(任意对象)
{
}
语句块中,或者在方法上加上synchronized修饰符
创建lock对象,使用lock.lock()方法进行加锁,我们要在创建一个Condition 对象作为这个锁的监听器
比如:
class BoundedBuffer {
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void put(Object x) throws InterruptedException {
lock.lock(); //上锁
try {
condition.await(); //使线程处于等待状态
方法体;
condition.signal(); // 唤醒线程
} finally {
lock.unlock(); //释放锁
}
}