Java-Thread
package com.thread; import java.util.Timer; import java.util.TimerTask; public class Threads extends Thread { public static void main(String[] args) { // 重写Thread类的run方法 Thread thread = new Thread() { public void run() { System.out.println("createThread……"); } }; thread.start(); // 实现runnable接口来启动一个线程,这种比较常用 Thread thread2 = new Thread(new Runnable() { public void run() { System.out.println("ImplementsRunnable……"); } }); thread2.start(); new Timer().schedule(new TimerTask() { @Override public void run() { // TODO Auto-generated method stub System.out.println("create Thread TimerTask()……"); } }, 2000); } }
设计两个线程,其中一个线程每次对j增加1,另外一个线程对j每次减少1。写出程序 有错欢迎指出。
package com.thread; public class ImplementsRunnable { private static int j; public static void main(String[] args) { jia(); } public static synchronized void inc() { j--; System.out.println(Thread.currentThread().getName()+"-inc"+j); } public static synchronized void dec() { j++; System.out.println(Thread.currentThread().getName()+"-dec"+j); } public static void jia() { new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i < 100; i++) { inc(); } } }).start(); new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i < 100; i++) { dec(); } } }).start(); } }