10. 11. 1. 线程同步 Test Synchronized method

来源:互联网 发布:java将string写入文件 编辑:程序博客网 时间:2024/05/20 07:14
 
public class TestSynchronized {int taskID;//任务IDpublic static void print(String msg){//定义一个打印方法System.out.println(Thread.currentThread().getName() + ":" + msg);}/** * val:十万牛顿每平米(英国压力单位) * VAL是自1980年代采用了Robert Gabillard教授发明的胶轮路轨系统技术, * 由法国马特拉公司(Matra)设计的一套专利轨道运输系统。 * 当然,这与本程序无关! */public synchronized void performATask(int val){//定义一个同步task任务taskID = val;print("之前:" + taskID);try{Thread.sleep(4000);//睡4秒,时间够长了...}catch(InterruptedException e){//这里没内容}print("之后:" + taskID);}public static void main(String[] args) throws Exception{//把所有异常都抛出,狠....final TestSynchronized tus = new TestSynchronized();Runnable runA = new Runnable(){public void run(){tus.performATask(1);//注意:开始调它的方法了,传ID为1}};Thread ta = new Thread(runA,"线程A");//我再调用你,ID为1的那个啊ta.start();Thread.sleep(2000);//又一个睡了Runnable runB = new Runnable(){public void run(){tus.performATask(2);//传给你ID  2}};Thread tb = new Thread(runB,"线程B");tb.start();}}/** * 线程A:之前:1线程A:之后:1线程B:之前:2线程B:之后:2 */