------- android培训、java培训、期待与您交流! ----------
import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; public class TraditionalTimerTest { private static int count = 0; public static void main(String[] args) { class MyTimerTask extends TimerTask{ @Override public void run() { count = (count+1)%2; System.out.println("bombing!"); //方法中新建一个计时器,执行本类任务 new Timer().schedule(new MyTimerTask(),2000+2000*count); } } //启动计时器 new Timer().schedule(new MyTimerTask(), 2000); while(true){ //每秒打印一次秒数 System.out.println(Calendar.getInstance().get(Calendar.SECOND));//new Date().getSeconds() try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
import java.util.Random; public class ThreadLocalTest { private static ThreadLocal<Integer> x = new ThreadLocal<Integer>(); public static void main(String[] args) { for(int i=0;i<2;i++){ new Thread(new Runnable(){ @Override public void run() { int data = new Random().nextInt(); System.out.println(Thread.currentThread().getName() + " has put data :" + data); //线程中向ThreadLocal中放的数据是和当前线程相关的 x.set(data); MyThreadScopeData.getThreadInstance().setName("name" + data); MyThreadScopeData.getThreadInstance().setAge(data); new A().get(); new B().get(); } }).start(); } } static class A{ public void get(){ int data = x.get(); System.out.println("A from " + Thread.currentThread().getName() + " get data :" + data); MyThreadScopeData myData = MyThreadScopeData.getThreadInstance(); System.out.println("A from " + Thread.currentThread().getName() + " getMyData: " + myData.getName() + "," + myData.getAge()); } } static class B{ public void get(){ int data = x.get(); System.out.println("B from " + Thread.currentThread().getName() + " get data :" + data); MyThreadScopeData myData = MyThreadScopeData.getThreadInstance(); System.out.println("B from " + Thread.currentThread().getName() + " getMyData: " + myData.getName() + "," + myData.getAge()); } } }将MyThreadLocalData封装成具有业务功能的对象,
class MyThreadScopeData{ private MyThreadScopeData(){} //静态的ThreadLocal实例,每个线程访问的是同一个map对象 private static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<MyThreadScopeData>(); //不需要加同步,因为对象是和线程相关的。 public static MyThreadScopeData getThreadInstance(){ MyThreadScopeData instance = map.get(); if(instance == null){ instance = new MyThreadScopeData(); map.set(instance); } return instance; } private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
小面试题
设计4个线程,其中2个线程每次对j增加1,另外2个线程每次对j减少1;public class ThreadTest1 { //定义j变量,成员位置 private int j; public static void main(String args[]){ //注意创建内部类对象的方法 ThreadTest1 tt=new ThreadTest1(); Inc inc=tt.new Inc(); Dec dec=tt.new Dec(); for(int i=0;i<2;i++){ Thread t=new Thread(inc); t.start(); t=new Thread(dec); t.start(); } } //将j++和j--封装成方法,可以加同步 private synchronized void inc(){ j++; System.out.println(Thread.currentThread().getName()+"-inc:"+j); } private synchronized void dec(){ j--; System.out.println(Thread.currentThread().getName()+"-dec:"+j); } //定义两个Runnable内部类,用于创建进程 class Inc implements Runnable{ public void run(){ for(int i=0;i<100;i++){ inc(); } } } class Dec implements Runnable{ public void run(){ for(int i=0;i<100;i++){ dec(); } } } }
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class ThreadPoolTest { /** * 学习线程池的操作 * @param args */ public static void main(String[] args) { //ExecutorService threadPool = Executors.newFixedThreadPool(3);//创建固定大小为3个线程的线程池 //ExecutorService threadPool = Executors.newCachedThreadPool();//创建一个可根据需要创建新线程的线程池 ExecutorService threadPool = Executors.newSingleThreadExecutor();//创建单一线程的线程池 for(int i=1;i<=10;i++){ final int task = i;//局部内部类访问i可以采取这种方法 threadPool.execute(new Runnable(){//execute接收一个Runnable对象,执行指定的任务 @Override public void run() { for(int j=1;j<=10;j++){ System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task of " + task); } } }); } System.out.println("all of 10 tasks have committed! "); //threadPool.shutdownNow();//关闭执行任务,返回未执行的任务列表,threadPool.shutdown();按顺序关闭任务 //用线程池启动定时器 Executors.newScheduledThreadPool(3).scheduleAtFixedRate( new Runnable(){ @Override public void run() { System.out.println("bombing!"); }}, 6, 2, TimeUnit.SECONDS); } }
public class CallableAndFuture { /** * @param args */ public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor();//创建一个线程池 Future<String> future = threadPool.submit(//通过线程池的submit方法提交Callable,返回future对象 new Callable<String>() { public String call() throws Exception { Thread.sleep(2000); return "hello"; }; } ); System.out.println("等待结果"); try { System.out.println("拿到结果:" + future.get());//通过future的get方法获得返回值 } catch (Exception e) { e.printStackTrace(); } ExecutorService threadPool2 = Executors.newFixedThreadPool(10); CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPool2); for(int i=1;i<=10;i++){ final int seq = i; completionService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { Thread.sleep(new Random().nextInt(5000)); return seq; } }); } for(int i=0;i<10;i++){ try { System.out.println( completionService.take().get());//take方法返回已经完成的future } catch (Exception e) { e.printStackTrace(); } } } }
------- android培训、java培训、期待与您交流! ----------