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的线程");
}
}
线程的创建
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的线程");
}
}
相关文章推荐
- Java多线程编程基础之线程对象
- java多线程基础
- java基础巩固训练营【第一轮】(十) 多线程 补充
- java多线程开发基础
- JAVA多线程编程基础1
- Java多线程基础知识
- 学习笔记7—Java基础5_多线程
- [零基础学JAVA]Java SE应用部分-25.多线程(03) 推荐
- [零基础学JAVA]Java SE应用部分-24.多线程(02) 推荐
- java基础——多线程
- java多线程基础
- 如何使用Java编写多线程程序-Java基础-Java-编程开发
- Java多线程编程基础
- [零基础学JAVA]Java SE应用部分-26.多线程(04) 推荐
- Java多线程程序设计入门-Java基础-Java-编程开发
- java多线程 基础(二) Thread Runnable
- java多线程基础
- 浅析Java多线程程序设计机制-Java基础-Java-编程开发
- Java基础很重要(四)---多线程
- Java多线程基础