Java基础--多线程

来源:互联网 发布:淘宝怎么充钱进去 编辑:程序博客网 时间:2024/05/16 01:26

线程是一个程序内容的顺序控制流。在一个时间点上,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类型具体可以查看APIt2.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的线程");}}

  


0 0
原创粉丝点击