Java多线程编码
多线程一直是编写程序代码的一个核心,Java中实现方法有以下两种:
一、继承自Thread
class Mythread extends Thread
[
//方法
public void run()
{
//内容
}
//……
}
开启线程时调用start()方法。
二、实现Runnable接口
class 类名 implements Runnable{
方法1;
方法2;
…
public void run(){
// other code…
}
属性1;
属性2;
…
}
三、线程同步
多线程往往牵扯到共享资源的问题,Java中可以通过同步代码块实现。
语法格式:
synchronized(同步对象){
//需要同步的代码
}
四、售票系统模拟
/** * @author Rollen-Holt * */ class hello implements Runnable { public void run() { for (int i = 0; i < 10; ++i) { sale(); } } public synchronized void sale() { if (count > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(count--); } } public static void main(String[] args) { hello he = new hello(); Thread h1 = new Thread(he); Thread h2 = new Thread(he); Thread h3 = new Thread(he); h1.start(); h2.start(); h3.start(); } private int count = 5; }