线程是一个程序里面不同的执行路径。
线程的的创建和启动
1. 定义线程类实现Runnable接口
public class TestThread1
{
public static void main(String arg[])
{
Runner1 r=new Runner1();
Thread t=new Thread(r); //Thread的实例来创建新的的线程
t.start(); //start方法来启动一个线程
for(int i=0;i<100;i++)
{
System.out.println("main-------------:"+ i);
}
}
}
class Runner1 implements Runnable //实现Runnable接口
{
public void run() //run操作线程
{
for(int i=0;i<100;i++)
{
System.out.println("Runner1:"+i);
}
}
}
2.定义Thread的子类并重写方法run()
public class TestThread1
{
public static void main(String arg[])
{
Runner1 t=new Runner1();
t.start(); //start方法来启动一个线程
for(int i=0;i<100;i++)
{
System.out.println("main-------------:"+ i);
}
}
}
class Runner1 extends Thread //实现thread的子类并重写run方法
{
public void run() //run操作线程
{
for(int i=0;i<100;i++)
{
System.out.println("Runner1:"+i);
}
}
} 从上面的代码可以看出java线程的特点:1.java的线程是通过java.lang.Thread类来实现。2.创建Thread的实例来创建新的线程。3.线程通过特定的Thread对象run()来操作。4.通过调用Thead类的start()来启动一个线程。
常用方法
sleep:让线程暂停执行。
举例:让程序每隔1秒打印一次。
import java.util.*;
public class TestInterrupt
{
public static void main(String arg[])
{
MyThread thread=new MyThread();
thread.start();
}
}
class MyThread extends Thread
{
boolean flag=true;
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("---"+1+"---");
try
{
sleep(1000); //程序会每隔1秒打印一次
}
catch(InterruptedException e)
{
return;
}
}
}
}
join:合并某个线程。
举例:t1和主程序合并执行。
public class TestJoin
{
public static void main(String arg[])
{
MyThread2 t1=new MyThread2("abcdef");
t1.start();
try
{
t1.join();
}
catch(InterruptedException e)
{
}
for(int i=1;i<=10;i++)
{
System.out.println("i am main");
}
}
}
class MyThread2 extends Thread
{
MyThread2(String s)
{
super(s);
}
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("i am "+getName());
try
{
sleep(1000);
}
catch(InterruptedException e)
{
return;
}
}
}
}
synchronized:给某个对象加锁,表示该对象只能有一个线程访问。
举例:两个进程同时访问一个对象。
public class TestSync implements Runnable{
Timer timer=new Timer();
public static void main(String arg[]){
TestSync test=new TestSync();
Thread t1=new Thread(test);
Thread t2=new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run()
{
timer.add(Thread.currentThread().getName());
}
}
class Timer
{
private static int num=0;
public synchronized void add(String name) //加锁,保证只有一个进程访问。
{
num++;
try
{
Thread.sleep(1);
}
catch(InterruptedException e){}
System.out.println(name+"you are"+num);
}
} 总结:java线程基础知识也就是这些,关键怎么去灵活将线程的思想融入到程序中,比如防止程序死锁,让程序的线程同步。原文地址:http://blog.csdn.net/suneqing/article/details/38663349