JavaAB线程类代码 java线程用法

java两个类A,B中分别都有一个线程 , 怎样能让A的线程中得到B类中线程的值,能举个简单的例子就最好了如果这线程不是做成死循环的,可利用JAVA的堆内存原理设置一下final static的对象 。如果这两个线程都是一直在跑的可考虑用JDK1.5以后有的concurrent包中的队列LinkedBlockingQueue对象实现一个线程保存,另一个线程取出 。当然这传和收线程的LinkedBlockingQueue对象必须是同一个 。
保存线程中用LinkedBlockingQueue对象的put方法将其添加到这个对象的队列中;
取出线程中代码片段:
BlockingQueueObject queue;
public void run() {
while(true){
ListObject list = new ArrayListObject();
try {
【JavaAB线程类代码 java线程用法】synchronized(Thread.currentThread()){
Thread.currentThread().wait(15000);
}
//waiter.await(5, TimeUnit.SECONDS);
int listSize = queue.drainTo(list, 2500);//用队列的方式将list中的数据一填充500个 , 一次操作填充500
if(listSize == 0){
continue;
}
//这里是具体的操作
logger.fatal("Get "+listSize+" ap5min object from Queue!");
list.clear();
/*list.add(obj);
if(list.size() == 100){
dao.batchSaveOrUpdate(list, 100);
list.clear();
}*/
} catch(Exception e) {
logger.error("保存数据出现异常:",e);
}
}
}
两个线程依次打印“A”,“B”,用java怎么实现?造个类a继承 thread
类a run方法 while(true)printf a
主线程 while(ture)printf b
然后类 a 和 主线程利用 wait 和notify 切换
java线程的经典代码package threadgroup;
class ThreadDemo3 extends Thread {
private String name;
private int delay;
public ThreadDemo3(String sname, int i_delay) {
name = sname;
delay = i_delay;
}
public void run() {
try {
sleep(delay);
} catch (InterruptedException e) {
}
System.out.println("多线程测试!\n" + name + "\n" + delay);
}
}
public class testMyThread {
public static void main(String[] args) {
ThreadDemo3 th1,th2,th3;
th1 = new ThreadDemo3("线程1", (int) (Math.random() * 900));
th2 = new ThreadDemo3("线程2", (int) (Math.random() * 900));
th3 = new ThreadDemo3("线程3", (int) (Math.random() * 900));
th1.start();
th2.start();
th3.start();
}
}
package threadgroup;
public class threadDemo {
public static void main(String[] args) {
Thread t = Thread.currentThread();
t.setName("你好吗?");
System.out.println("正在进行的Thread是:" + t);
try {
for (int i = 0; i5; i++) {
System.out.println("我不叫穆继超" + i);
Thread.sleep(3000);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("Thread has wrong" + e.getMessage());
}
}
}
package threadgroup;
public class threadDemo2 implements Runnable {
public threadDemo2() {
Thread t1 = Thread.currentThread();
t1.setName("第一个主进程");
System.out.println("正在运行" + t1);
Thread t2 = new Thread(this, "");
System.out.println("在创建一个进程");
t2.start();
try {
System.out.println("使他进入第一个睡眠状态");
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("Thread has wrong" + e.getMessage());
}
System.out.println("退出第一个进程");
}
public void run() {
try {
for (int i = 0; i5; i++) {
System.out.println("进程" + i);
Thread.sleep(3000);
}
} catch (InterruptedException e) {
// TODO: handle exception
System.out.println("Thread has wrong" + e.getMessage());

推荐阅读