浅谈Java线程学习 (三)

2014-11-24 11:22:25 · 作者: · 浏览: 14
);
System.out.print("main is finished !"); //测试main函数里的执行顺序,说明thread A、B和main函数是并发的线程。thread有个睡眠等待的过程,所以main函数就先执行了
}


}

package moreThread;

public class ThreadWaitingJion extends Thread{
String s ;
int m, i = 0 ;
/**
* 构造函数
* @param s
*/
public ThreadWaitingJion(String s) {
super();
this.s = s;
}

/**
* 功能实现函数:连续输出一组字符,并间隔睡眠一段随机时间
*/
public void run() {
try
{
for(i = 0 ;i<6;i++)
{

Thread.sleep((int)(500*Math.random())); //线程每次睡眠的时间为一个随机值500*Math.random()
System.out.print(s);

}
System.out.print(s+"has finished!");
}
catch(InterruptedException e) {
return;
}
}

public static void main (String args[]) {
ThreadWaitingJion threadA = new ThreadWaitingJion("A "); //调用构造函数来构造两个对象
ThreadWaitingJion threadB = new ThreadWaitingJion("B ");
threadA.start();
try
{
threadA.join(); //jion()方法的功能是先执行完一个线程,然后再去执行另一个线程
}
catch(InterruptedException e) {}
threadB.start();
System.out.print("main is finished !"); //测试main函数里的执行顺序,说明thread A、B和main函数是并发的线程。thread有个睡眠等待的过程,所以main函数就先执行了
}


}
结果:


[java]
A A A A A A A has finished!main is finished !B B B B B B B has finished!

A A A A A A A has finished!main is finished !B B B B B B B has finished!
4、线程同步

模拟银行取款系统:


[java]
package moreThread;


class Cbank{
private static int s = 2000;
/**
* 实现同步操作的方式是在共享内存变量的方法前加synchronized修饰符。在程序运行过程中,如果某一线程调用
* 经synchronized修饰的方法,在该线程结束此方法之前,其他所有线程都不能运行该方法,只有等待太线程完成此方法的
* 运行后,其他线程才能运行该方法。
* 相当于,系统暂时为该方法中的变量加锁,使得其他的线程无法存取该变量。
* @param m //所取款数目
*/
public synchronized static void sub (int m) {
int temp = s;
temp-=m;
try {
Thread.sleep((int)(1000*Math.random())); //随机睡眠1000*Math.random()时间
}
catch(InterruptedException e) { }

s=temp;
System.out.print(s+" || ");
}
}

class Customer extends Thread {
public void run() {
for(int i= 1; i <= 4; i++) {
Cbank.sub(100);
}
}
}

public class ThreadCogradient {
public static void main (String srgs[]) {
Customer customer1 = new Customer();
Customer customer2 = new Customer();
customer1.start();
customer2.start();
}

}

package moreThread;


class Cbank{
private static int s = 2000;
/**
* 实现同步操作的方式是在共享内存变量的方法前加synchronized修饰符。在程序运行过程中,如果某一线程调用
* 经synchronized修饰的方法,在该线程结束此方法之前,其他所有线程都不能运行该方法,只有等待太线程完成此方法的
* 运行后,其他线程才能运行该方法。
* 相当于,系统暂时为该方法中的变量加锁,使得其他的线程无法存取该变量。
* @param m //所取款数目
*/
public synchronized static void sub (int m) {
int temp = s;
temp-=m;
try {
Thread.sleep((int)(1000*Math.random())); //随机睡眠1000*Math.random()时间
}
catch(InterruptedException e) { }

s=temp;
System.out.print(s+" || ");
}
}

class Customer extends Thread {
public void run() {
for(int i= 1; i <= 4; i++) {
Cbank.sub(100);
}
}
}

public class ThreadCogradient {
public static void main (String srgs[]) {
Customer customer1 = new Customer();
Customer customer2 = new Customer();
customer1.start();
customer2.start();
}

}
结果:[java]
1900 || 1800 || 1700 || 1600 || 1500 || 1400 || 1300 || 1200 ||

1900 || 1800 || 1700 || 1600 || 1500 || 1400 || 1300 || 1200 ||