//示例1
import java.lang.Thread;
import java.lang.InterruptedException;
class Test1 extends Thread{
public void run(){
try{
for(int i=0;i<10;i++){
System.out.println("正在做第1件事情。。。。");
this.sleep(500);
}
System.out.println("1.....Over.**************************");
}
catch(InterruptedException ex){
ex.printStackTrace();
}
}
}
class Test2 extends Thread{
public void run(){
try{
for(int i=0;i<10;i++){
System.out.println("正在做第2件事情。。。。");
this.sleep(500);
}
System.out.println("2.....Over.**************************");
}
catch(InterruptedException ex){
ex.printStackTrace();
}
}
}
public class ThreadDemo{
public static void main(String args[]){
Test1 t1=new Test1();
Test2 t2=new Test2();
t1.start();
t2.start();
}
}
//示例2
import java.lang.Runnable;
import java.lang.InterruptedException;
//import java.lang.Thread;
class Test1 implements Runnable{
public void run(){
try{
for(int i=0;i<10;i++){
System.out.println("在做第1件事情。。。");
Thread.sleep(500);
}
System.out.println(" 1..Over ***********************");
}
catch(InterruptedException ex){
ex.printStackTrace();
}
}
}
class Test2 implements Runnable{
public void run(){
try{
for(int i=0;i<10;i++){
System.out.println("在做第2件事情。。。");
Thread.sleep(500);
}
System.out.println(" 2..Over ***********************");
}
catch(InterruptedException ex){
ex.printStackTrace();
}
}
}
public class RunnableDemo{
public static void main(String args[]){
Test1 t1=new Test1();
Test2 t2=new Test2();
Thread thread1=new Thread(t1);
Thread thread2=new Thread(t2);
thread1.start();
thread2.start();
}
}
//示例3,同步
import java.lang.Thread;
import java.lang.InterruptedException;
class Test extends Thread{
String who;
DoTest obj;
public Test(){
}
public Test(String who,DoTest obj){
this.who=who;
this.obj=obj;
}
public void run(){
this.obj.gotoSchool(this.who);
}
}
class DoTest{
//同步方法
synchronized void gotoSchool(String who)
{
try
{
System.out.println(who+"上卫生间....请稍候... ");
Thread.sleep(2000); //上卫生间蹲2秒
System.out.println(who+"上卫生间 完毕 \n");
}
catch(InterruptedException e)
{
System.out.println("中断");
}
&nbs