您的位置:首页 > 编程语言 > Java开发

Java基础--多线程

2016-09-13 18:29 369 查看
线程是一个程序内容的顺序控制流。在一个时间点上,CPU只有一个线程在进行。

线程的创建

     1.定义线程类实现Runnable接口

     2.Thread myThread=new Thread(target) // target为Runnable接口类型

     3.Runnable中只有一个方法:public void run();可以定义线程运行体

     public class TestThread{
public static void main(String[] args){
Runner r=new Runner();
Thread t=new Thread(r);
t.start();

}
}
class Runner implements Runnable{
public void run(){

}
}
锁()

  这和数据库的原子性很相似,防止一个线程被另一个资源打断,我们需要给程序加一把锁,一旦锁定,必须把程序执行完才能执行其他方法。

  下面是一个加锁的例子。

  public class TestSync implements Runnable{
Timer timer=new Timer(); //new一个timer对象
public static void main(String[] args){
TestSync test=new TestSync(); //实现runnable接口
Thread t1=new Thread(test);
Thread t2=new Thread(test);
t1.setName("t1"); //thread 的getName方法,传入类型为String类型具体可以查看API
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){ // synchronized 同步的 线程

num++;
try{
Thread.sleep(1);
}catch(InterruptedException e){

}
System.out.println(name+", 你是第 "+num+" 个使用timer的线程");
}
}
  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: