浅谈Java线程学习 (二)

2014-11-24 11:22:25 · 作者: · 浏览: 16
是在接口调用,注意与thread子类调用的方法有什么不同之处
count++;
if(count>=20) {
break;
}
}
System.out.print(s+"has finished!");
}
catch(InterruptedException e) {
return;
}
}
结果:


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

A B main is finished !A A B A A B A A B A A B A A B A A B A A B A A B A A B A A has finished!B B B B B B B B B B B has finished!
3、线程的等待

一、各线程并发执行


[java]
package moreThread;

public class ThreadWaiting extends Thread{
String s ;
int m, i = 0 ;

public ThreadWaiting(String s) {
super();
this.s = s;
}

public void run() {
try
{
for(i = 0 ;i<6;i++)
{

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

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

public static void main (String args[]) {
ThreadWaiting threadA = new ThreadWaiting("A "); //调用构造函数来构造两个对象
ThreadWaiting threadB = new ThreadWaiting("B ");
threadA.start();
threadB.start();
System.out.print("main is finished !"); //测试main函数里的执行顺序,说明thread A、B和main函数是并发的线程。thread有个睡眠等待的过程,所以main函数就先执行了
}

}

package moreThread;

public class ThreadWaiting extends Thread{
String s ;
int m, i = 0 ;

public ThreadWaiting(String s) {
super();
this.s = s;
}

public void run() {
try
{
for(i = 0 ;i<6;i++)
{

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

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

public static void main (String args[]) {
ThreadWaiting threadA = new ThreadWaiting("A "); //调用构造函数来构造两个对象
ThreadWaiting threadB = new ThreadWaiting("B ");
threadA.start();
threadB.start();
System.out.print("main is finished !"); //测试main函数里的执行顺序,说明thread A、B和main函数是并发的线程。thread有个睡眠等待的过程,所以main函数就先执行了
}

}
结果


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

main is finished !B B A A B A B A B B B has finished!A A A has finished!
二、jion()方法的功能


[java]
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(